PyQT clicked events only executes at start and never works again

Question:

I just started learning PyQT and using it with PySide2. I got the idea of how button events work with binding clicked events, however, I have a problem.

My click events execute randomly on startup -don’t understand either- and after the execution clicking these QButtons does not invoke binded methods.

class StartWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.button_orginial = QPushButton('Show Original')
        self.button_orginial.setStyleSheet("background-color: #4592af; color: black;")
        self.button_prediction = QPushButton('Show Prediction')
        self.button_prediction.setStyleSheet("background-color: #e3c4a8; color: black;")

        self.horizontalLayout = QHBoxLayout()
        self.verticalLayout = QVBoxLayout()

        self.verticalLayout.addWidget(self.button_orginial)
        self.verticalLayout.addWidget(self.button_prediction)

        self.verticalLayout.addLayout(self.horizontalLayout)

        self.button_prediction.clicked.connect(self.ShowPrediction())
        self.button_orginial.clicked.connect(self.ShowOriginal())

        self.InitWindow()
   

    def InitWindow(self):
        self.setWindowTitle("xxx")    
        self.setGeometry(500,500,940,360)
        self.setLayout(self.verticalLayout)

    def ShowPrediction(self):
        self.predictImg = QLabel(self)
        self.predictImg.setPixmap(self.genImage("prediction"))
        self.horizontalLayout.addWidget(self.predictImg)
        print("pred clicked")
    
    def ShowOriginal(self):
        self.showImage = QLabel(self)
        self.showImage.setPixmap(self.genImage("original"))
        self.horizontalLayout.addWidget(self.showImage)
        print("org clicked")
    
if __name__ == '__main__':
    app = QApplication([])
    window = StartWindow()
    window.setStyleSheet("background-color: black;")
    #window.showFullScreen()
    window.show()
    app.exit(app.exec_())
Asked By: Oğulcan Çelik

||

Answers:

Change this:

self.button_prediction.clicked.connect(self.ShowPrediction())
self.button_orginial.clicked.connect(self.ShowOriginal())

To this:

self.button_prediction.clicked.connect(self.ShowPrediction)
self.button_orginial.clicked.connect(self.ShowOriginal)

What you’re doing is trying to bind the value returned by your callbacks to the clicked signal, which is wrong. This is also why the callbacks are triggered once the program starts, since you’re asking them to be evaluated before passing them to connect.

You want to bind the function object to the clicked signal.

Answered By: Paul M.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.