PyQt5 QListWidget选择多项并返回text内容

实现多选

通过setSelectionMode 可以实现ctrl+ 鼠标左键多选

 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)  # 设置之后可以通过ctrl+ 鼠标左键多选
        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内容

这里有两种方法

  1. 方法1
item.setText(name)  # 设置
item_name = item.text() # 获取
  1. 方法2
item.setData(Qt.UserRole, name)  # 设置
item_name = item.data(Qt.UserRole) # 获取

你可能感兴趣的:(PyQt5 QListWidget选择多项并返回text内容)