Skip to content Skip to sidebar Skip to footer

Pyqt5 Making Dynamic Widgets Clickable And Pass Arguments To Another Function

I am trying to make dynamic widgets and make them clickable. By clicking on one widget it should pass dynamic value to other widget. I have tried sender() and other options accessi

Solution 1:

To simplify the task we will create 2 widgets, the first one will be ClickableWidget that will have a signal indicating the number associated with the widget, whereas the second DynamicWidget will have a method that will be in charge of updating the number of widgets.

To know if an element is pressed we use the method installEventFilter() and eventFilter(), this filters the events giving information of the object and event, we will use setProperty("index", ) to store the number.

In the second widget I have implemented a method that is responsible for cleaning the widgets and creating some new widgets.

classClickableWidget(QWidget):
    clicked = pyqtSignal(int)
    def__init__(self, n=5, parent=None):
        QWidget.__init__(self, parent)
        self.hlayout = QVBoxLayout(self)
        for i inrange(n):
            label = QLabel("btn {}".format(i), self)
            label.setProperty("index", i)
            self.hlayout.addWidget(label)
            label.installEventFilter(self)

    defeventFilter(self, obj, event):
        ifisinstance(obj, QLabel) and event.type() == QEvent.MouseButtonPress:
            i = obj.property("index") 
            self.clicked.emit(i)
        return QWidget.eventFilter(self, obj, event)

classDynamicWidget(QWidget):
    def__init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.hlayout = QVBoxLayout(self)

    defchangeWidget(self, n):
        defclearLayout(layout):
            item = layout.takeAt(0)
            while item:
                w = item.widget()
                if w:
                    w.deleteLater()
                lay = item.layout()
                if lay:
                    clearLayout(item.layout())
                item = layout.takeAt(0)

        clearLayout(self.hlayout)
        for i inrange(n):
            label = QLabel("btn {}".format(i), self)
            self.hlayout.addWidget(label)


classScreen(QWidget):
    def__init__(self):
        super(Screen, self).__init__()
        self.layout = QHBoxLayout(self)
        c = ClickableWidget(6, self)
        d = DynamicWidget(self)
        c.clicked.connect(d.changeWidget)
        self.layout.addWidget(c)
        self.layout.addWidget(d)

Post a Comment for "Pyqt5 Making Dynamic Widgets Clickable And Pass Arguments To Another Function"