简体   繁体   English

如何在 PyQt5 的 QlistWidget 中返回项目的值

[英]how to return the value of item in the QlistWidget in PyQt5

I have a GUI app in PyQt5 that create display items with checkboxes in a QlistWidget where the user check on the item and the system print the checked values.我在 PyQt5 中有一个 GUI 应用程序,它在 QlistWidget 中创建带有复选框的显示项目,其中用户检查项目并且系统打印检查的值。

The problem is that when the user check the items it display the below error:问题是当用户检查项目时,它会显示以下错误:

  print([i.text() for i in self.checked])
AttributeError: 'str' object has no attribute 'text'

But this line print([i.text() for i in self.checked]) print the values only in the print但是这一行print([i.text() for i in self.checked])仅在打印中打印值

this line is the error:这一行是错误:

self.checked = [i.text() for i in self.checked]

code:代码:

from PyQt5 import QtCore, QtGui, QtWidgets

import os
import pandas as pd
import numpy as np

import chardet




class Ui_MainWindow(QtWidgets.QMainWindow):
    def setupUi(self, MainWindow):
        self.checked = []
        
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        
        self.header_list = QtWidgets.QListWidget(self.centralwidget)
        self.header_list.setMaximumSize(QtCore.QSize(120, 1667))
        self.header_list.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
        self.header_list.setObjectName("header_list")
        self.header_list.itemChanged.connect(self.selectionChanged)
        
        MainWindow.setCentralWidget(self.centralwidget)
        
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")

        self.menufile = self.menubar.addMenu("File")
        self.menufile.setObjectName("menufile")

        self.menuimportfile = QtWidgets.QAction("Import File",self.menufile)
        self.menuimportfile.setObjectName("importfile")
        self.menuimportfile.triggered.connect(lambda:self.loadFile())
        
        MainWindow.setMenuBar(self.menubar)
        
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        
        MainWindow.setStatusBar(self.statusbar)
        
        self.menufile.addAction(self.menuimportfile)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.menufile.setTitle(_translate("MainWindow", "file"))


    def loadFile(self):
        try:
            fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open File", "", "Excel Files (*.csv *.xls *.xlsx)");
            print(fileName)            
            name, ext = os.path.splitext(fileName)
            print("name: {} ".format(name))
            print("ext:  {} ".format(ext))
            if ext == ".csv":
                with open(fileName, 'rb') as rawdata:
                    result = chardet.detect(rawdata.read(100000))
                print(result)
                df = pd.read_csv(fileName,encoding = result["encoding"])
            elif ext == ".xls" or ext == ".xlsx":
                df = pd.read_excel(fileName)
            self.df = df

            
        #part that display items in the qlistWidget
            self.header_list.clear()
            savelist = list(self.df)
            for item in savelist:
                qitem = QtWidgets.QListWidgetItem ( ) 
                qitem.setText ( item ) 
                qitem. setFlags ( QtCore. Qt . ItemIsUserCheckable | QtCore. Qt . ItemIsEnabled ) 
                qitem.setCheckState ( QtCore.Qt.Unchecked ) 
                self.header_list.addItem ( qitem )
        
        except Exception as e:
            print("error is {}".format(e))


    def selectionChanged(self, item):
        if item.checkState():
            if item not in self.checked:
                self.checked.append(item)
        elif item in self.checked:
            self.checked.remove(item)
        print([i.text() for i in self.checked])
        self.checked = [i.text() for i in self.checked]
        print(self.checked)
        


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
  

The problem is trivial, it is assumed that in the variable "checked" you want to save the QListWidgetItem that have been checked.问题很简单,假设在变量“checked”中要保存已检查的 QListWidgetItem。 Let's analyze what happens with an example: let's say that the user selects the first option, then "checked" will be empty initially so the checked item is compared and added to the list but later checked is a list of the texts of the QListWidgetItem, which denatures the logic.让我们通过一个例子来分析发生了什么:假设用户选择了第一个选项,然后“checked”最初将为空,因此选中的项目被比较并添加到列表中,但后来检查的是 QListWidgetItem 的文本列表,这使逻辑变性。 So as a lesson don't use the same variable for multiple things:因此,作为一个教训,不要对多个事物使用相同的变量:

def selectionChanged(self, item):
    if item.checkState():
        if item not in self.checked:
            self.checked.append(item)
    elif item in self.checked:
        self.checked.remove(item)

    values = [i.text() for i in self.checked] print(values)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中使用Pyqt5在qlistwidget中获取项目的行号 - how to get the row number of an item in the qlistwidget using Pyqt5 in python 如何从 Qlistwidget 获取 select 项目,并更新 Pyqt5 中的文本框? - How to select item from Qlistwidget , and update textbox in Pyqt5? 单击QListWidget中的列表项后如何触发function? PyQt5 - How to trigger a function after clicking on a list item in a QListWidget? PyQt5 QListWidget项上面的PyQt5 cursor如何弹出WhatsThis文档? - How PyQt5 cursor above QListWidget item pops WhatsThis documentation? 如何从 pyqt5 中的 QListWidget 返回实际的 object - How to return the actual object from a QListWidget in pyqt5 PyQt5 检查项目是否已经在 QListWidget 中 - PyQt5 check if item is already in QListWidget PyQt5:将按钮添加到 QListWidget 的每个项目 - PyQt5: Add button to each item of a QListWidget pyqt5 问题 如何将数据从 qlistwidget 点击项传递到另一个 .py 文件? - pyqt5 problem How to pass data from qlistwidget click item to another .py file? 在 PyQt5 的 QListWidget 中,如何仅在用户选择项目时显示工具提示? - In PyQt5's QListWidget, how can I only show the tooltip for an item when the user chooses it? 如何检查QlistWidget中的项目并在python pyqt5中的选定项目上运行函数 - how to check item in QlistWidget and run function on the selected items in python pyqt5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM