實現(xiàn)多選
通過setSelectionMode
可以實現(xiàn)ctrl+ 鼠標(biāo)左鍵
多選
self.listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
完整代碼
from PyQt5.QtCore import QEvent, Qt, QSize, pyqtSignal
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import *
class Dialog_01(QMainWindow):
def __init__(self):
super(QMainWindow,self).__init__()
myQWidget = QWidget()
myBoxLayout = QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidget = QListWidget()
self.listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) # 設(shè)置之后可以通過ctrl+ 鼠標(biāo)左鍵多選
self.listWidget.itemClicked.connect(self.printCurrentItems)
for i in range(3):
item=QListWidgetItem()
name='A'+'%04d'%i
item.setText(name)
item.setData(Qt.UserRole, name)
self.listWidget.addItem(item)
myBoxLayout.addWidget(self.listWidget)
def printCurrentItems(self, item):
print('-----mouse choose:------')
items = self.listWidget.selectedItems()
for item in items:
item_name = item.data(Qt.UserRole)
print('choose item:', item_name)
item_name2 = item.text()
print('choose item_name2:', item_name2)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(720, 480)
sys.exit(app.exec_())
獲取QListWidget內(nèi)容
這里有兩種方法
- 方法1
item.setText(name) # 設(shè)置
item_name = item.text() # 獲取
- 方法2
item.setData(Qt.UserRole, name) # 設(shè)置
item_name = item.data(Qt.UserRole) # 獲取