今天学习了下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. OpenCV摄像头人脸识别

    注: 从外设摄像装置中获取图像帧,把每帧的图片与人脸特征进行匹配,用方框框住识别出来的人脸 需要用到的函数: CvHaarClassifierCascade* cvLoadHaarClassifier ...

  2. 取数据的前N行

    用awk中csv文件中取前1000行出来,代码虽少,很容易出错 BEGIN{ FS=","; OFS=","; i=; } { i++; )exit; prin ...

  3. HackerRank savita-and-friends

    Description 在一条边上求一个点,使得这个点到所有点的最长的最短距离 最短. \(n \leqslant 10^5\) Sol Dijkstra+扫描线+单调队列. 这个好像叫什么最小直径生 ...

  4. 5 HandlerIterator处理程序迭代器类——Live555源码阅读(一)基本组件类

    这是Live555源码阅读的第一部分,包括了时间类,延时队列类,处理程序描述类,哈希表类这四个大类. 本文由乌合之众 lym瞎编,欢迎转载 my.oschina.net/oloroso Handler ...

  5. HDU 1160 DP最长子序列

    G - FatMouse's Speed Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64 ...

  6. PowerDesigner V16.5 安装文件

    之前在网上找个假的,只能看,不能创建自己的DB; 或者 不能破解的,比较伤脑筋. 偶在这里提供一个 可长期使用的版本. PowerDesigner165_破解文件.rar    链接:http://p ...

  7. 【Networking】k8s容器网络 && golang相关

    Bookmarks flannel/proxy.c at master · coreos/flannel kubernetes/kubernetes: Production-Grade Contain ...

  8. javascript特殊运算符

    in运算符                 in运算符要求其左边的运算数是一个字符串,或可以被转换为字符串,右边的运算数十一个对象或数组.如果该 运算符左边的值是右边对象的一个属性名,则返回true, ...

  9. ERROR Cannot determine the location of the VS Common Tools Folder

    参考:ERROR Cannot determine the location of the VS Common Tools Folder   http://blog.csdn.net/m3728975 ...

  10. 关于Intent ,Task, Activity的理解

    看到一篇好文章,待加工 http://hi.baidu.com/jieme1989/item/6e5f41d3f65be848ddf9beb9 第三篇 http://blog.csdn.net/luo ...