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);
new QListWidgetItem(tr("Fir"), listWidget);
new QListWidgetItem(tr("Pine"), listWidget);If you need to insert a new item into the list at a particular position, it is more required to construct the item without a parent widget and use the insertItem() function to place it within the list. The list widget will take ownership of the item.

QListWidgetItem *newItem = new QListWidgetItem;
newItem->setText(itemText);
listWidget->insertItem(row, newItem);For multiple items, insertItems() can be used instead. The number of items in the list is found with the count() function. To remove items from the list, use takeItem().

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

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <ui version="4.0">
  3  <class>PyPath</class>
  4  <widget class="QWidget" name="PyPath">
  5   <property name="geometry">
  6    <rect>
  7     <x>0</x>
  8     <y>0</y>
  9     <width>735</width>
 10     <height>401</height>
 11    </rect>
 12   </property>
 13   <property name="windowTitle">
 14    <string>Form</string>
 15   </property>
 16   <widget class="QGroupBox" name="groupBox">
 17    <property name="geometry">
 18     <rect>
 19      <x>40</x>
 20      <y>20</y>
 21      <width>651</width>
 22      <height>301</height>
 23     </rect>
 24    </property>
 25    <property name="title">
 26     <string>系统环境变量</string>
 27    </property>
 28    <widget class="QWidget" name="verticalLayoutWidget_2">
 29     <property name="geometry">
 30      <rect>
 31       <x>20</x>
 32       <y>20</y>
 33       <width>621</width>
 34       <height>261</height>
 35      </rect>
 36     </property>
 37     <layout class="QVBoxLayout" name="verticalLayout_2">
 38      <item>
 39       <layout class="QHBoxLayout" name="horizontalLayout">
 40        <item>
 41         <widget class="QListWidget" name="listWidgetPath"/>
 42        </item>
 43        <item>
 44         <layout class="QVBoxLayout" name="verticalLayout">
 45          <item>
 46           <widget class="QPushButton" name="btnAdd">
 47            <property name="text">
 48             <string>Add(&amp;A)</string>
 49            </property>
 50           </widget>
 51          </item>
 52          <item>
 53           <widget class="QPushButton" name="btnRemove">
 54            <property name="text">
 55             <string>Remove(&amp;R)</string>
 56            </property>
 57           </widget>
 58          </item>
 59          <item>
 60           <widget class="QPushButton" name="btnUp">
 61            <property name="text">
 62             <string>Move Up(&amp;U)</string>
 63            </property>
 64           </widget>
 65          </item>
 66          <item>
 67           <widget class="QPushButton" name="btnMovedown">
 68            <property name="text">
 69             <string>Move Down(&amp;D)</string>
 70            </property>
 71           </widget>
 72          </item>
 73          <item>
 74           <spacer name="verticalSpacer">
 75            <property name="orientation">
 76             <enum>Qt::Vertical</enum>
 77            </property>
 78            <property name="sizeHint" stdset="0">
 79             <size>
 80              <width>20</width>
 81              <height>180</height>
 82             </size>
 83            </property>
 84           </spacer>
 85          </item>
 86         </layout>
 87        </item>
 88       </layout>
 89      </item>
 90      <item>
 91       <layout class="QHBoxLayout" name="horizontalLayout_2">
 92        <item>
 93         <widget class="QLabel" name="label">
 94          <property name="text">
 95           <string>说明:</string>
 96          </property>
 97         </widget>
 98        </item>
 99        <item>
100         <widget class="QTextEdit" name="textEditExplain"/>
101        </item>
102        <item>
103         <spacer name="horizontalSpacer">
104          <property name="orientation">
105           <enum>Qt::Horizontal</enum>
106          </property>
107          <property name="sizeHint" stdset="0">
108           <size>
109            <width>10</width>
110            <height>20</height>
111           </size>
112          </property>
113         </spacer>
114        </item>
115       </layout>
116      </item>
117     </layout>
118    </widget>
119   </widget>
120   <widget class="QPushButton" name="btnClose">
121    <property name="geometry">
122     <rect>
123      <x>500</x>
124      <y>350</y>
125      <width>75</width>
126      <height>23</height>
127     </rect>
128    </property>
129    <property name="text">
130     <string>Close</string>
131    </property>
132   </widget>
133   <widget class="QPushButton" name="btnHelp">
134    <property name="geometry">
135     <rect>
136      <x>600</x>
137      <y>350</y>
138      <width>75</width>
139      <height>23</height>
140     </rect>
141    </property>
142    <property name="text">
143     <string>Help(&amp;H)</string>
144    </property>
145   </widget>
146   <widget class="QLabel" name="labelURL">
147    <property name="geometry">
148     <rect>
149      <x>20</x>
150      <y>380</y>
151      <width>81</width>
152      <height>16</height>
153     </rect>
154    </property>
155    <property name="text">
156     <string>by dcb3688</string>
157    </property>
158   </widget>
159  </widget>
160  <resources/>
161  <connections>
162   <connection>
163    <sender>btnClose</sender>
164    <signal>clicked()</signal>
165    <receiver>PyPath</receiver>
166    <slot>close()</slot>
167    <hints>
168     <hint type="sourcelabel">
169      <x>546</x>
170      <y>358</y>
171     </hint>
172     <hint type="destinationlabel">
173      <x>449</x>
174      <y>362</y>
175     </hint>
176    </hints>
177   </connection>
178  </connections>
179 </ui>

Ctrl+R 查看效果图

转换为py文件:

  1 # -*- coding: utf-8 -*-
  2 
  3 # Form implementation generated from reading ui file 'listwidget.ui'
  4 #
  5 # Created: Wed Feb 04 15:21:06 2015
  6 #      by: PyQt4 UI code generator 4.10.3
  7 #
  8 # WARNING! All changes made in this file will be lost!
  9 
 10 from PyQt4 import QtCore, QtGui
 11 
 12 try:
 13     _fromUtf8 = QtCore.QString.fromUtf8
 14 except AttributeError:
 15     def _fromUtf8(s):
 16         return s
 17 
 18 try:
 19     _encoding = QtGui.QApplication.UnicodeUTF8
 20     def _translate(context, text, disambig):
 21         return QtGui.QApplication.translate(context, text, disambig, _encoding)
 22 except AttributeError:
 23     def _translate(context, text, disambig):
 24         return QtGui.QApplication.translate(context, text, disambig)
 25 
 26 class Ui_PyPath(object):
 27     def setupUi(self, PyPath):
 28         PyPath.setObjectName(_fromUtf8("PyPath"))
 29         PyPath.resize(735, 401)
 30         self.groupBox = QtGui.QGroupBox(PyPath)
 31         self.groupBox.setGeometry(QtCore.QRect(40, 20, 651, 301))
 32         self.groupBox.setObjectName(_fromUtf8("groupBox"))
 33         self.verticalLayoutWidget_2 = QtGui.QWidget(self.groupBox)
 34         self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(20, 20, 621, 261))
 35         self.verticalLayoutWidget_2.setObjectName(_fromUtf8("verticalLayoutWidget_2"))
 36         self.verticalLayout_2 = QtGui.QVBoxLayout(self.verticalLayoutWidget_2)
 37         self.verticalLayout_2.setMargin(0)
 38         self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
 39         self.horizontalLayout = QtGui.QHBoxLayout()
 40         self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
 41         self.listWidgetPath = QtGui.QListWidget(self.verticalLayoutWidget_2)
 42         self.listWidgetPath.setObjectName(_fromUtf8("listWidgetPath"))
 43         self.horizontalLayout.addWidget(self.listWidgetPath)
 44         self.verticalLayout = QtGui.QVBoxLayout()
 45         self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
 46         self.btnAdd = QtGui.QPushButton(self.verticalLayoutWidget_2)
 47         self.btnAdd.setObjectName(_fromUtf8("btnAdd"))
 48         self.verticalLayout.addWidget(self.btnAdd)
 49         self.btnRemove = QtGui.QPushButton(self.verticalLayoutWidget_2)
 50         self.btnRemove.setObjectName(_fromUtf8("btnRemove"))
 51         self.verticalLayout.addWidget(self.btnRemove)
 52         self.btnUp = QtGui.QPushButton(self.verticalLayoutWidget_2)
 53         self.btnUp.setObjectName(_fromUtf8("btnUp"))
 54         self.verticalLayout.addWidget(self.btnUp)
 55         self.btnMovedown = QtGui.QPushButton(self.verticalLayoutWidget_2)
 56         self.btnMovedown.setObjectName(_fromUtf8("btnMovedown"))
 57         self.verticalLayout.addWidget(self.btnMovedown)
 58         spacerItem = QtGui.QSpacerItem(20, 180, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
 59         self.verticalLayout.addItem(spacerItem)
 60         self.horizontalLayout.addLayout(self.verticalLayout)
 61         self.verticalLayout_2.addLayout(self.horizontalLayout)
 62         self.horizontalLayout_2 = QtGui.QHBoxLayout()
 63         self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
 64         self.label = QtGui.QLabel(self.verticalLayoutWidget_2)
 65         self.label.setObjectName(_fromUtf8("label"))
 66         self.horizontalLayout_2.addWidget(self.label)
 67         self.textEditExplain = QtGui.QTextEdit(self.verticalLayoutWidget_2)
 68         self.textEditExplain.setObjectName(_fromUtf8("textEditExplain"))
 69         self.horizontalLayout_2.addWidget(self.textEditExplain)
 70         spacerItem1 = QtGui.QSpacerItem(10, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
 71         self.horizontalLayout_2.addItem(spacerItem1)
 72         self.verticalLayout_2.addLayout(self.horizontalLayout_2)
 73         self.btnClose = QtGui.QPushButton(PyPath)
 74         self.btnClose.setGeometry(QtCore.QRect(500, 350, 75, 23))
 75         self.btnClose.setObjectName(_fromUtf8("btnClose"))
 76         self.btnHelp = QtGui.QPushButton(PyPath)
 77         self.btnHelp.setGeometry(QtCore.QRect(600, 350, 75, 23))
 78         self.btnHelp.setObjectName(_fromUtf8("btnHelp"))
 79         self.labelURL = QtGui.QLabel(PyPath)
 80         self.labelURL.setGeometry(QtCore.QRect(20, 380, 81, 16))
 81         self.labelURL.setObjectName(_fromUtf8("labelURL"))
 82 
 83         self.retranslateUi(PyPath)
 84         QtCore.QObject.connect(self.btnClose, QtCore.SIGNAL(_fromUtf8("clicked()")), PyPath.close)
 85         QtCore.QMetaObject.connectSlotsByName(PyPath)
 86 
 87     def retranslateUi(self, PyPath):
 88         PyPath.setWindowTitle(_translate("PyPath", "Form", None))
 89         self.groupBox.setTitle(_translate("PyPath", "系统环境变量", None))
 90         self.btnAdd.setText(_translate("PyPath", "Add(&A)", None))
 91         self.btnRemove.setText(_translate("PyPath", "Remove(&R)", None))
 92         self.btnUp.setText(_translate("PyPath", "Move Up(&U)", None))
 93         self.btnMovedown.setText(_translate("PyPath", "Move Down(&D)", None))
 94         self.label.setText(_translate("PyPath", "说明:", None))
 95         self.btnClose.setText(_translate("PyPath", "Close", None))
 96         self.btnHelp.setText(_translate("PyPath", "Help(&H)", None))
 97         self.labelURL.setText(_translate("PyPath", "by dcb3688", None))
 98 
 99 
100 if __name__ == "__main__":
101     import sys
102     app = QtGui.QApplication(sys.argv)
103     PyPath = QtGui.QWidget()
104     ui = Ui_PyPath()
105     ui.setupUi(PyPath)
106     PyPath.show()
107     sys.exit(app.exec_())

二. 新建逻辑页面

新建逻辑页面为 mainlist.py

引入ui

1 from listwidget import Ui_PyPath

通过Python的内置函数获取系统的环境变量

1 os.environ["PATH"]

拆分PATH字符串生成列表

通过ListWidget的 addItems方法添加到列表中

1 pathV = os.environ["PATH"]
2 splitPath = pathV.split(';')
3 self.UI.listWidgetPath.addItems(splitPath)  # 添加列表框项

通过 itemClicked(QListWidgetItem *) 信号触发meit 事件

1 self.connect(self.UI.listWidgetPath, SIGNAL('itemClicked(QListWidgetItem *)'), self.itemClicked)  # 点击事件

逻辑页面完整代码:

  1 # -*- coding: utf-8 -*-
  2 
  3 import sys
  4 from PyQt4.QtCore import *
  5 from PyQt4.QtGui import *
  6 from listwidget import Ui_PyPath
  7 import icoqrc
  8 import os
  9 class mainlist(QWidget):
 10     def __init__(self, parent=None):
 11         super(mainlist, self).__init__(parent)
 12         self.UI = Ui_PyPath()
 13         self.UI.setupUi(self)
 14         self.setWindowTitle('ListWidget')
 15         self.setWindowIcon(QIcon(':qq.ico'))
 16         self.setFixedSize(self.width(), self.height())
 17         self.setWindowFlags(Qt.WindowMinimizeButtonHint)
 18         pathV = os.environ["PATH"]
 19         splitPath = pathV.split(';')
 20         self.UI.listWidgetPath.addItems(splitPath)  # 添加列表框项
 21         self.connect(self.UI.listWidgetPath, SIGNAL('itemClicked(QListWidgetItem *)'), self.itemClicked)  # 点击事件
 22         self.connect(self.UI.listWidgetPath, SIGNAL('itemDoubleClicked (QListWidgetItem *)'), self.itemDoubleClicked)  #  双击事件
 23         self.connect(self.UI.btnAdd, SIGNAL('clicked()'), self.btnAdd)  # 新建
 24         self.connect(self.UI.btnRemove, SIGNAL('clicked()'), self.btnRemove)  # 移除
 25         self.connect(self.UI.btnUp, SIGNAL('clicked()'), self.btnMoveup)  # 上移
 26         self.connect(self.UI.btnMovedown, SIGNAL('clicked()'), self.btnMovedown)  # 下移
 27         self.UI.labelURL.setOpenExternalLinks(True)
 28         self.UI.labelURL.setText('<a href="http://dcb3688.cnblogs.com/"><b style="color:#0000ff;">by dcb3688</b></a></body></html>')   
 29         self.connect(self.UI.btnHelp, SIGNAL('clicked()'), self.cnblog)  # 跳转到cnblogs
 30 
 31     # 列表单击事件
 32     def itemClicked(self):
 33         acurrent=str(self.UI.listWidgetPath.currentItem().text())  # 获取当前item的文本
 34         if acurrent.find('System32') >= 0:
 35             self.UI.textEditExplain.setText(u'系统目录:'+acurrent)
 36         elif acurrent.find('SVN') >= 0:
 37             self.UI.textEditExplain.setText(u'版本控制器Svn:'+acurrent)
 38         elif acurrent.find('Git') >= 0:
 39             self.UI.textEditExplain.setText(u'版本控制器Git:'+acurrent)
 40         elif acurrent.find('Windows') >= 0:
 41             self.UI.textEditExplain.setText(u'系统目录:'+acurrent)
 42         elif acurrent.find('Python') >= 0:
 43             self.UI.textEditExplain.setText(u'Python安装目录:'+acurrent)
 44         else:
 45             self.UI.textEditExplain.setText(u'未识别')
 46     # 列表双击事件
 47     def itemDoubleClicked(self):
 48         QMessageBox.question(self, (u'提示'),(u'item的双击事件!'),QMessageBox.Yes)
 49 
 50     # 新建操作
 51     def btnAdd(self):
 52         # 预定义对话框
 53         DialogText, Ok = QInputDialog.getText(self, u'新建环境变量', u'请输入环境变量路径:')
 54         if Ok:
 55             # 获取当前的列, 判断在新建之前是否选中过list
 56             GetCurrentRow = self.UI.listWidgetPath.currentRow()
 57             if GetCurrentRow:
 58                 self.UI.listWidgetPath.insertItem(GetCurrentRow, DialogText)
 59             else:
 60                 self.UI.listWidgetPath.insertItem(0, DialogText)
 61 
 62     # 移除操作
 63     def btnRemove(self):
 64         GetCurrentRow = self.UI.listWidgetPath.currentRow()
 65         if not GetCurrentRow:
 66             QMessageBox.warning(self, (u'提示'),(u'请先选择移除的List!'), QMessageBox.Yes)
 67         else:
 68             Ok= QMessageBox.warning(self, (u'提示'),(u'确定要移除该List吗?'), QMessageBox.Yes, QMessageBox.No)
 69             if Ok==QMessageBox.Yes:
 70                 self.UI.listWidgetPath.takeItem(GetCurrentRow)  # 移除
 71 
 72     # 上移
 73     def btnMoveup(self):
 74         GetCurrentRow = self.UI.listWidgetPath.currentRow()
 75         if GetCurrentRow > 0:
 76             newRow = GetCurrentRow-1  # 索引号减1
 77             takeSelf=self.UI.listWidgetPath.takeItem(GetCurrentRow)  # 取元素值,并在新索引位置插入
 78             self.UI.listWidgetPath.insertItem(newRow, takeSelf)
 79             #设置当前元素索引为新插入位置,可以使得元素连续上移
 80             self.UI.listWidgetPath.setCurrentRow(newRow)
 81 
 82 
 83     # 下移
 84     def btnMovedown(self):
 85         GetCurrentRow = self.UI.listWidgetPath.currentRow()
 86         if GetCurrentRow < self.UI.listWidgetPath.count():
 87             newRow = GetCurrentRow+1
 88             self.UI.listWidgetPath.insertItem(newRow, self.UI.listWidgetPath.takeItem(GetCurrentRow))
 89             self.UI.listWidgetPath.setCurrentRow(newRow)
 90 
 91 
 92 
 93 
 94     # 打开cnblogs
 95     def cnblog(self):
 96         QDesktopServices.openUrl(QUrl('http://dcb3688.cnblogs.com/p/4273444.html'))
 97     def keyPressEvent(self, event):
 98         if event.key() == Qt.Key_Escape:
 99             self.close()
100 
101 if __name__ == '__main__':
102     app = QApplication(sys.argv)
103     mainclass = mainlist()
104     mainclass.show()
105     app.exec_()

三. 运行效果

四. 问题

这个问题是关于Python获取系统环境变量问题,既然能获取系统环境变量相应的应该也可修改或新增环境变量,本例子中仅获取环境变量,新增只是ListWidget的例子,没有真正修改系统的环境变量,所以下次在编辑本片文章就是新增修改系统环境变量的问题!

原文地址:https://www.cnblogs.com/dcb3688/p/4273444.html