从我的自定义QListWidgetItem获取QtWidgets

时间:2018-09-26 16:20:02

标签: python pyqt pyqt5 qlistwidget

我有一个自定义窗口小部件(ProjectWidget),它代表我企业的不同项目,它们显示在QListWidget中。我想使用复选框选择某些项目以对它们进行分析。

当我单击Analyze Projects按钮时,它将调用analytics()函数,该函数将遍历QListWidget的QListWidgetitems。

我不知道如何访问组成我的自定义窗口小部件的窗口小部件。在我的示例中,我需要检查该复选框是否实际上已选中,是否从构成我的自定义窗口小部件的其他窗口小部件中获取标签文本。

这是程序的外观: enter image description here

相关代码:

#Custom Widget
class ProjectWidget(QWidget):
    def __init__(self, parent=None):
        super(ProjectWidget, self).__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

    def addDetails(self, project):
        self.ui.projectNumber.setText(project.projectNumber)
        self.ui.projectDescription.setText(project.description)
        self.ui.closingDate.setText(project.closingDate)


class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()

    def loadProjects(self):
        self.ui.listWidget.clear()

        print("loading projects")
        projects = WCA.getCurrentProjects(session)

        #Add custom widget to listwidget
        for x in range(len(projects)):
             #I create an Item*
            Item = QListWidgetItem(self.ui.listWidget)
            #I create a custom widget*
            Item_Widget = ProjectWidget()
            Item_Widget.addDetails(projects[x])
            #I set the Size from the Item to the same of the widget*
            Item.setSizeHint(Item_Widget.size())
            self.ui.listWidget.addItem(Item)
            self.ui.listWidget.setItemWidget(Item, Item_Widget)

        print(str(len(projects)) + " Projects loaded.")

    def analyze(self):
        print("Analyze projects")
        #Check if more than one project is selected
        for i in range(self.ui.listWidget.count()):
            item = self.ui.listWidget.item(i)
            #Check if the custom widget's checkbox is checked
            print(item)

1 个答案:

答案 0 :(得分:0)

您必须通过传递itemWidget()来使用QListWidgetItem方法来获取小部件:

def analyze(self):
    print("Analyze projects")
    #Check if more than one project is selected
    for i in range(self.ui.listWidget.count()):
        item = self.ui.listWidget.item(i)
        widget = self.ui.listWidget.itemWidget(item)
        if widget is not None:
            if widget.ui.name_of_checkbox.isChecked():
                print(widget)