今天学习了下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

 <?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(&amp;A)</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnRemove">
<property name="text">
<string>Remove(&amp;R)</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnUp">
<property name="text">
<string>Move Up(&amp;U)</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnMovedown">
<property name="text">
<string>Move Down(&amp;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(&amp;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 展示系统环境变量的更多相关文章

  1. 使用VBScript实现设置系统环境变量的小程序

    本人有点桌面洁癖,桌面上只放很少的东西,很多软件都用快捷键调出.最近频繁用到一个软件,我又不想放个快捷方式在桌面,也不想附到开始菜单,于是乎想将其所在目录附加到系统环境变量Path上,以后直接在运行中 ...

  2. 配置windows 系统PHP系统环境变量

    1. 首先到php官网下载php-5.3.6-nts-Win32-VC9-x86.ZIP 解压到电脑硬盘.将文件解压到文件夹php5.3.6下载地址:http://www.php.net/downlo ...

  3. Mac 系统环境变量配置

    Mac 系统环境变量配置 例如这里要配置一下 QUICK_V3_ROOT 的环境变量 1.打开终端 输入  vim ~/.bash_profile 2.一直回车 知道出现以下选项 按 E 编辑     ...

  4. Visual Studio 2012系统环境变量设置(命令行)

    方法1.运行脚本vsvars32.bat:D:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\vsvars32.bat ...

  5. bat批处理设置Java JDK系统环境变量文件

    自己修改第3行的Java安装目录就可以设置JAVA_HOME, classPath,追加到PATH的最前面 JAVA_HOME=C:\Program Files\Java\jdk1.6.0_10 cl ...

  6. [Java] JDK 系统环境变量设置 bat

    @echo off set regpath=HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environmen ...

  7. OpenCV的安装与系统环境变量

    OpenCV的安装与系统环境变量 安装OpenCV本来是很简单的一件事,但配置却很麻烦.而且在配置过程中尤为重要的步骤就是系统环境变量的配置.我使用的是CodeBlick13.12与OpenCV1.0 ...

  8. DOS永久设置系统环境变量-WMIC

    wmic Windows Management Instrumentation Command-line(Windows管理规范命令行) WMIC扩展WMI(Windows Management In ...

  9. linux系统环境变量.bash_profile/bashrc文件

    系统环境变量的查看: [root@localhost ~]# envHOSTNAME=localhost.localdomainSELINUX_ROLE_REQUESTED=TERM=xtermSHE ...

随机推荐

  1. hiho #1372:平方求 (bfs)

    #1372 : 平方求和 时间限制:1000ms 单点时限:1000ms 内存限制:256MB 描述 对于一个非负整数n,最少需要几个完全平方数,使其和为n? 输入 输入包含多组数据.对于每组数据: ...

  2. 剑指Offer 合并两个排序的链表

    题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则.   思路: 用2个新节点,一个用来存放新链表的头节点,另一个用来移动.当p1,p2有一个到尾部的 ...

  3. 剑指Offer 矩形覆盖

    题目描述 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形.请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?   解法,还是斐波那契数列   AC代码: class So ...

  4. Spatial pyramid pooling (SPP)-net (空间金字塔池化)笔记(转)

    在学习r-cnn系列时,一直看到SPP-net的身影,许多有疑问的地方在这篇论文里找到了答案. 论文:Spatial Pyramid Pooling in Deep Convolutional Net ...

  5. DOM高级

    表格应用 获取 tBodies, tHead, tFoot, rows, cells 隔行变色 鼠标移入高亮, 添加,删除一行 DOM的方法使用 <!DOCTYPE html PUBLIC &q ...

  6. js弹出提示信息,然后跳转到另一页面

    <script language="javascript">  alert("您的用户名与密码已成功修改!");  document.locatio ...

  7. SHAREPOINT - CAML列表查询

    首先要了解的是CAML(Collaboration Application Markup Language)不仅仅是用在对列表.文档库的查询,字段的定义,站点定义等处处使用的都是CAML. 简单的提一 ...

  8. dubbo main方法启动

    public static void main(String[] args) { com.alibaba.dubbo.container.Main.main(args); } 以上就可以简单本地启动了

  9. 如何在maven中添加本地jar包

    mvn install:install-file -DgroupId=mytest-DartifactId=test-Dversion=1.1 -Dpackaging=jar -Dfile=d:\te ...

  10. java web 学习 --第八天(Java三级考试)

    第七天的学习内容:http://www.cnblogs.com/tobecrazy/p/3464231.html EL表达式 EL : Expression Language 使用EL表达式可以减少& ...