Search code examples
pythonpyqtpyqt5qlistwidget

Getting QtWidgets from my custom QListWidgetItem


I have a custom widget (ProjectWidget) that represents different projects for my business and they are displayed inside a QListWidget. I want to select certain projects using the checkbox to do an analysis on them.

When I click the Analyze Projects button it calls the analyze() function which iterates through the QListWidgetitems of the QListWidget.

I can't figure out how to access the widgets that make up my custom widget. In my example I need to check if the checkbox is in fact checked and if so get the the label text from the other widgets that make up my custom widget.

This is what the program looks like: enter image description here

Revelant code:

#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)

Solution

  • You have to use the itemWidget() method by passing the QListWidgetItem to get the widget:

    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)