我就废话不多说了,大家还是直接看代码吧~
实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
class Win(QWidget):
def __init__( self ):
super (Win, self ).__init__()
self .setObjectName( "self" )
self .resize( 400 , 300 )
self .listWidget = QtWidgets.QListWidget( self )
self .listWidget.setGeometry(QtCore.QRect( 10 , 20 , 256 , 192 ))
self .listWidget.setObjectName( "listWidget" )
self .pushButton = QtWidgets.QPushButton( self )
self .pushButton.setGeometry(QtCore.QRect( 280 , 60 , 75 , 23 ))
self .pushButton.setObjectName( "pushButton" )
self .pushButton.clicked.connect( self .add)
self .retranslateUi()
QtCore.QMetaObject.connectSlotsByName( self )
def retranslateUi( self ):
_translate = QtCore.QCoreApplication.translate
self .setWindowTitle(_translate( "self" , "self" ))
self .pushButton.setText(_translate( "self" , "PushButton" ))
def add( self ):
self .listWidget.addItem( '123' )
index = self .listWidget.currentRow() + 1
if index:
self .listWidget.item(index - 1 ).setBackground(QColor( 'green' ))
self .listWidget.item(index).setBackground(QColor( 'red' ))
else :
self .listWidget.item(index).setBackground(QColor( 'blue' ))
self .listWidget.setCurrentRow( self .listWidget.currentRow() + 1 )
app = QApplication(sys.argv)
win = Win()
win.show()
sys.exit(app.exec_())
|
补充:PyQt QListWidget 删除item的坑
使用removeItemWidget函数需要QListWidgetItem的对象本身作为参数,通过findItems得到了对象,调用了函数,但是还是没反应,PyQt5的bug?
使用takeItem删除成功了
1
2
3
4
|
item = self .listWidget.findItems( '张三' ,Qt.MatchExactly)[ 0 ]
row = self .listWidget.row(item)
print (row)
self .listWidget.takeItem(row)
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/qq_26669719/article/details/80590359