今天學習了下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
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(&A)</string> 49 </property> 50 </widget> 51 </item> 52 <item> 53 <widget class="QPushButton" name="btnRemove"> 54 <property name="text"> 55 <string>Remove(&R)</string> 56 </property> 57 </widget> 58 </item> 59 <item> 60 <widget class="QPushButton" name="btnUp"> 61 <property name="text"> 62 <string>Move Up(&U)</string> 63 </property> 64 </widget> 65 </item> 66 <item> 67 <widget class="QPushButton" name="btnMovedown"> 68 <property name="text"> 69 <string>Move Down(&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(&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的例子,沒有真正修改系統的環境變量,所以下次在編輯本片文章就是新增修改系統環境變量的問題!
