Pyqt QListWidget 展示系统环境变量
今天学习了下Pyqt的 QListWidget 控件
我们先看下这个图片

这张图片就是典型的listWidget效果,我们今天就仿这样布局新建个ListWidget
在网上找了个关于QListWidget的基础关系图:

官网对QListWidget的描述:
|
The QListWidget class provides an item-based list widget. QListWidget is a convenience class that provides a list view similar to the one supplied by QListView, but with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. For a more flexible list view widget, use the QListView class with a standard model. List widgets are constructed in the same way as other widgets: QListWidget *listWidget = new QListWidget(this);The selectionMode() of a list widget determines how many of the items in the list can be selected at the same time, and whether complex selections of items can be created. This can be set with the setSelectionMode() function. There are two ways to add items to the list: they can be constructed with the list widget as their parent widget, or they can be constructed with no parent widget and added to the list later. If a list widget already exists when the items are constructed, the first method is easier to use: new QListWidgetItem(tr("Oak"), listWidget); QListWidgetItem *newItem = new QListWidgetItem; The current item in the list can be found with currentItem(), and changed with setCurrentItem(). The user can also change the current item by navigating with the keyboard or clicking on a different item. When the current item changes, the currentItemChanged() signal is emitted with the new current item and the item that was previously current. |
QListWidget继承自QListView, 所以ListWidget继承了QListView的所有方法
下面我们就用QListWidget做一个查看系统环境变量的小例子
一. 创建Ui
listwidget.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PyPath</class>
<widget class="QWidget" name="PyPath">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>735</width>
<height>401</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QGroupBox" name="groupBox">
<property name="geometry">
<rect>
<x>40</x>
<y>20</y>
<width>651</width>
<height>301</height>
</rect>
</property>
<property name="title">
<string>系统环境变量</string>
</property>
<widget class="QWidget" name="verticalLayoutWidget_2">
<property name="geometry">
<rect>
<x>20</x>
<y>20</y>
<width>621</width>
<height>261</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QListWidget" name="listWidgetPath"/>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QPushButton" name="btnAdd">
<property name="text">
<string>Add(&A)</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnRemove">
<property name="text">
<string>Remove(&R)</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnUp">
<property name="text">
<string>Move Up(&U)</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnMovedown">
<property name="text">
<string>Move Down(&D)</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>180</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>说明:</string>
</property>
</widget>
</item>
<item>
<widget class="QTextEdit" name="textEditExplain"/>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>10</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<widget class="QPushButton" name="btnClose">
<property name="geometry">
<rect>
<x>500</x>
<y>350</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Close</string>
</property>
</widget>
<widget class="QPushButton" name="btnHelp">
<property name="geometry">
<rect>
<x>600</x>
<y>350</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Help(&H)</string>
</property>
</widget>
<widget class="QLabel" name="labelURL">
<property name="geometry">
<rect>
<x>20</x>
<y>380</y>
<width>81</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>by dcb3688</string>
</property>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>btnClose</sender>
<signal>clicked()</signal>
<receiver>PyPath</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>546</x>
<y>358</y>
</hint>
<hint type="destinationlabel">
<x>449</x>
<y>362</y>
</hint>
</hints>
</connection>
</connections>
</ui>
Ctrl+R 查看效果图

转换为py文件:
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'listwidget.ui'
#
# Created: Wed Feb 04 15:21:06 2015
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig) class Ui_PyPath(object):
def setupUi(self, PyPath):
PyPath.setObjectName(_fromUtf8("PyPath"))
PyPath.resize(735, 401)
self.groupBox = QtGui.QGroupBox(PyPath)
self.groupBox.setGeometry(QtCore.QRect(40, 20, 651, 301))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.verticalLayoutWidget_2 = QtGui.QWidget(self.groupBox)
self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(20, 20, 621, 261))
self.verticalLayoutWidget_2.setObjectName(_fromUtf8("verticalLayoutWidget_2"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.verticalLayoutWidget_2)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.listWidgetPath = QtGui.QListWidget(self.verticalLayoutWidget_2)
self.listWidgetPath.setObjectName(_fromUtf8("listWidgetPath"))
self.horizontalLayout.addWidget(self.listWidgetPath)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.btnAdd = QtGui.QPushButton(self.verticalLayoutWidget_2)
self.btnAdd.setObjectName(_fromUtf8("btnAdd"))
self.verticalLayout.addWidget(self.btnAdd)
self.btnRemove = QtGui.QPushButton(self.verticalLayoutWidget_2)
self.btnRemove.setObjectName(_fromUtf8("btnRemove"))
self.verticalLayout.addWidget(self.btnRemove)
self.btnUp = QtGui.QPushButton(self.verticalLayoutWidget_2)
self.btnUp.setObjectName(_fromUtf8("btnUp"))
self.verticalLayout.addWidget(self.btnUp)
self.btnMovedown = QtGui.QPushButton(self.verticalLayoutWidget_2)
self.btnMovedown.setObjectName(_fromUtf8("btnMovedown"))
self.verticalLayout.addWidget(self.btnMovedown)
spacerItem = QtGui.QSpacerItem(20, 180, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.horizontalLayout.addLayout(self.verticalLayout)
self.verticalLayout_2.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label = QtGui.QLabel(self.verticalLayoutWidget_2)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_2.addWidget(self.label)
self.textEditExplain = QtGui.QTextEdit(self.verticalLayoutWidget_2)
self.textEditExplain.setObjectName(_fromUtf8("textEditExplain"))
self.horizontalLayout_2.addWidget(self.textEditExplain)
spacerItem1 = QtGui.QSpacerItem(10, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.btnClose = QtGui.QPushButton(PyPath)
self.btnClose.setGeometry(QtCore.QRect(500, 350, 75, 23))
self.btnClose.setObjectName(_fromUtf8("btnClose"))
self.btnHelp = QtGui.QPushButton(PyPath)
self.btnHelp.setGeometry(QtCore.QRect(600, 350, 75, 23))
self.btnHelp.setObjectName(_fromUtf8("btnHelp"))
self.labelURL = QtGui.QLabel(PyPath)
self.labelURL.setGeometry(QtCore.QRect(20, 380, 81, 16))
self.labelURL.setObjectName(_fromUtf8("labelURL")) self.retranslateUi(PyPath)
QtCore.QObject.connect(self.btnClose, QtCore.SIGNAL(_fromUtf8("clicked()")), PyPath.close)
QtCore.QMetaObject.connectSlotsByName(PyPath) def retranslateUi(self, PyPath):
PyPath.setWindowTitle(_translate("PyPath", "Form", None))
self.groupBox.setTitle(_translate("PyPath", "系统环境变量", None))
self.btnAdd.setText(_translate("PyPath", "Add(&A)", None))
self.btnRemove.setText(_translate("PyPath", "Remove(&R)", None))
self.btnUp.setText(_translate("PyPath", "Move Up(&U)", None))
self.btnMovedown.setText(_translate("PyPath", "Move Down(&D)", None))
self.label.setText(_translate("PyPath", "说明:", None))
self.btnClose.setText(_translate("PyPath", "Close", None))
self.btnHelp.setText(_translate("PyPath", "Help(&H)", None))
self.labelURL.setText(_translate("PyPath", "by dcb3688", None)) if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
PyPath = QtGui.QWidget()
ui = Ui_PyPath()
ui.setupUi(PyPath)
PyPath.show()
sys.exit(app.exec_())
二. 新建逻辑页面
新建逻辑页面为 mainlist.py
引入ui
from listwidget import Ui_PyPath
通过Python的内置函数获取系统的环境变量
os.environ["PATH"]
拆分PATH字符串生成列表
通过ListWidget的 addItems方法添加到列表中
pathV = os.environ["PATH"]
splitPath = pathV.split(';')
self.UI.listWidgetPath.addItems(splitPath) # 添加列表框项
通过 itemClicked(QListWidgetItem *) 信号触发meit 事件
self.connect(self.UI.listWidgetPath, SIGNAL('itemClicked(QListWidgetItem *)'), self.itemClicked) # 点击事件
逻辑页面完整代码:
# -*- coding: utf-8 -*- import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from listwidget import Ui_PyPath
import icoqrc
import os
class mainlist(QWidget):
def __init__(self, parent=None):
super(mainlist, self).__init__(parent)
self.UI = Ui_PyPath()
self.UI.setupUi(self)
self.setWindowTitle('ListWidget')
self.setWindowIcon(QIcon(':qq.ico'))
self.setFixedSize(self.width(), self.height())
self.setWindowFlags(Qt.WindowMinimizeButtonHint)
pathV = os.environ["PATH"]
splitPath = pathV.split(';')
self.UI.listWidgetPath.addItems(splitPath) # 添加列表框项
self.connect(self.UI.listWidgetPath, SIGNAL('itemClicked(QListWidgetItem *)'), self.itemClicked) # 点击事件
self.connect(self.UI.listWidgetPath, SIGNAL('itemDoubleClicked (QListWidgetItem *)'), self.itemDoubleClicked) # 双击事件
self.connect(self.UI.btnAdd, SIGNAL('clicked()'), self.btnAdd) # 新建
self.connect(self.UI.btnRemove, SIGNAL('clicked()'), self.btnRemove) # 移除
self.connect(self.UI.btnUp, SIGNAL('clicked()'), self.btnMoveup) # 上移
self.connect(self.UI.btnMovedown, SIGNAL('clicked()'), self.btnMovedown) # 下移
self.UI.labelURL.setOpenExternalLinks(True)
self.UI.labelURL.setText('<a href="http://dcb3688.cnblogs.com/"><b style="color:#0000ff;">by dcb3688</b></a></body></html>')
self.connect(self.UI.btnHelp, SIGNAL('clicked()'), self.cnblog) # 跳转到cnblogs # 列表单击事件
def itemClicked(self):
acurrent=str(self.UI.listWidgetPath.currentItem().text()) # 获取当前item的文本
if acurrent.find('System32') >= 0:
self.UI.textEditExplain.setText(u'系统目录:'+acurrent)
elif acurrent.find('SVN') >= 0:
self.UI.textEditExplain.setText(u'版本控制器Svn:'+acurrent)
elif acurrent.find('Git') >= 0:
self.UI.textEditExplain.setText(u'版本控制器Git:'+acurrent)
elif acurrent.find('Windows') >= 0:
self.UI.textEditExplain.setText(u'系统目录:'+acurrent)
elif acurrent.find('Python') >= 0:
self.UI.textEditExplain.setText(u'Python安装目录:'+acurrent)
else:
self.UI.textEditExplain.setText(u'未识别')
# 列表双击事件
def itemDoubleClicked(self):
QMessageBox.question(self, (u'提示'),(u'item的双击事件!'),QMessageBox.Yes) # 新建操作
def btnAdd(self):
# 预定义对话框
DialogText, Ok = QInputDialog.getText(self, u'新建环境变量', u'请输入环境变量路径:')
if Ok:
# 获取当前的列, 判断在新建之前是否选中过list
GetCurrentRow = self.UI.listWidgetPath.currentRow()
if GetCurrentRow:
self.UI.listWidgetPath.insertItem(GetCurrentRow, DialogText)
else:
self.UI.listWidgetPath.insertItem(0, DialogText) # 移除操作
def btnRemove(self):
GetCurrentRow = self.UI.listWidgetPath.currentRow()
if not GetCurrentRow:
QMessageBox.warning(self, (u'提示'),(u'请先选择移除的List!'), QMessageBox.Yes)
else:
Ok= QMessageBox.warning(self, (u'提示'),(u'确定要移除该List吗?'), QMessageBox.Yes, QMessageBox.No)
if Ok==QMessageBox.Yes:
self.UI.listWidgetPath.takeItem(GetCurrentRow) # 移除 # 上移
def btnMoveup(self):
GetCurrentRow = self.UI.listWidgetPath.currentRow()
if GetCurrentRow > 0:
newRow = GetCurrentRow-1 # 索引号减1
takeSelf=self.UI.listWidgetPath.takeItem(GetCurrentRow) # 取元素值,并在新索引位置插入
self.UI.listWidgetPath.insertItem(newRow, takeSelf)
#设置当前元素索引为新插入位置,可以使得元素连续上移
self.UI.listWidgetPath.setCurrentRow(newRow) # 下移
def btnMovedown(self):
GetCurrentRow = self.UI.listWidgetPath.currentRow()
if GetCurrentRow < self.UI.listWidgetPath.count():
newRow = GetCurrentRow+1
self.UI.listWidgetPath.insertItem(newRow, self.UI.listWidgetPath.takeItem(GetCurrentRow))
self.UI.listWidgetPath.setCurrentRow(newRow) # 打开cnblogs
def cnblog(self):
QDesktopServices.openUrl(QUrl('http://dcb3688.cnblogs.com/p/4273444.html'))
def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape:
self.close() if __name__ == '__main__':
app = QApplication(sys.argv)
mainclass = mainlist()
mainclass.show()
app.exec_()
三. 运行效果

四. 问题
这个问题是关于Python获取系统环境变量问题,既然能获取系统环境变量相应的应该也可修改或新增环境变量,本例子中仅获取环境变量,新增只是ListWidget的例子,没有真正修改系统的环境变量,所以下次在编辑本片文章就是新增修改系统环境变量的问题!
Pyqt QListWidget 展示系统环境变量的更多相关文章
- 使用VBScript实现设置系统环境变量的小程序
本人有点桌面洁癖,桌面上只放很少的东西,很多软件都用快捷键调出.最近频繁用到一个软件,我又不想放个快捷方式在桌面,也不想附到开始菜单,于是乎想将其所在目录附加到系统环境变量Path上,以后直接在运行中 ...
- 配置windows 系统PHP系统环境变量
1. 首先到php官网下载php-5.3.6-nts-Win32-VC9-x86.ZIP 解压到电脑硬盘.将文件解压到文件夹php5.3.6下载地址:http://www.php.net/downlo ...
- Mac 系统环境变量配置
Mac 系统环境变量配置 例如这里要配置一下 QUICK_V3_ROOT 的环境变量 1.打开终端 输入 vim ~/.bash_profile 2.一直回车 知道出现以下选项 按 E 编辑 ...
- Visual Studio 2012系统环境变量设置(命令行)
方法1.运行脚本vsvars32.bat:D:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\vsvars32.bat ...
- bat批处理设置Java JDK系统环境变量文件
自己修改第3行的Java安装目录就可以设置JAVA_HOME, classPath,追加到PATH的最前面 JAVA_HOME=C:\Program Files\Java\jdk1.6.0_10 cl ...
- [Java] JDK 系统环境变量设置 bat
@echo off set regpath=HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environmen ...
- OpenCV的安装与系统环境变量
OpenCV的安装与系统环境变量 安装OpenCV本来是很简单的一件事,但配置却很麻烦.而且在配置过程中尤为重要的步骤就是系统环境变量的配置.我使用的是CodeBlick13.12与OpenCV1.0 ...
- DOS永久设置系统环境变量-WMIC
wmic Windows Management Instrumentation Command-line(Windows管理规范命令行) WMIC扩展WMI(Windows Management In ...
- linux系统环境变量.bash_profile/bashrc文件
系统环境变量的查看: [root@localhost ~]# envHOSTNAME=localhost.localdomainSELINUX_ROLE_REQUESTED=TERM=xtermSHE ...
随机推荐
- Linux中的动态库和静态库(.a/.la/.so/.o)
Linux中的动态库和静态库(.a/.la/.so/.o) Linux中的动态库和静态库(.a/.la/.so/.o) C/C++程序编译的过程 .o文件(目标文件) 创建atoi.o 使用atoi. ...
- linux操作系统flash player问题--ubuntu
adobe公司停止了对linux系统的flash player的更新,这导致很多网页视频不能够通过浏览器观看,很是不爽! 还好,给用户留下了一点点希望,那便是chrome浏览器. 谷歌浏览器,有一款插 ...
- Tomcat部署Web应用的两种方式
WEB工程目录结构 部署方式一:此种方式部署,jsp页面修改后,不能动态更新,需要重新部署才能看到效果.不过可以配置动态更新实现. 部署方式二:此种方式部署,jsp修改后,直接在页面可以看到效果.(因 ...
- bootstrap框架----像素
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 转帖:如何建立与使用 Window setup project
原文地址: http://www.codeproject.com/Articles/12548/Visual-Studio-Windows-Application-Setup-Project
- 在Py文件中引入django环境
复制manage.py中的相关代码即可并将文件置于Project文件夹(与manage.py同位置)下 示例: #! /usr/bin/env python # -*- coding:utf- -*- ...
- 开始学习C++
这里突然想起来当初学习java和C# 总是会有个demo : hello world. 这里我记得我曾经看过一个笑话.说有个程序员,想学习书法,买了笔墨,都准备好了,但是不知道写什么好.最后,他大 ...
- storm单机环境部署
前面说过storm集群的部署,这篇主要介绍storm单机环境部署,其实他们之间很类似,就是将之前配置文件中所有的集群条目改成本机的地址即可,部署之前应该按前面solr和zookeeper单机环境部署那 ...
- 6.SpringMVC注解启用
SpringMVC注解可以帮助我们快速地注入 属性和参数 提高开发效率. 由于 有相当一部分人讨厌xml配置方式 注解可以覆盖 xml则不能 使用注解比xml规范化,因为很多注解都是java的规范的范 ...
- SQL Server 2008登录错误:无法连接到(local)的解决方法
1.服务器类型我们选择了“数据库引擎”时,查找里面的可登录用户名是没有的,下边的服务器名称只显示为“(local)”,连“Windows 身份验证”都无法登录. 如果朋友们和我出错的问题是一样请看下面 ...