【问题标题】:PyQT clicked events only executes at start and never works again [duplicate]PyQT点击事件仅在开始时执行并且永远不会再次工作[重复]
【发布时间】:2020-01-06 08:29:19
【问题描述】:

我刚开始学习 PyQT 并将它与 PySide2 一起使用。我了解了按钮事件如何与绑定单击事件一起工作,但是,我遇到了一个问题。

我的点击事件在启动时随机执行 - 也不明白 - 执行后点击这些 QButtons 不会调用绑定方法。

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("SmartAlpha")    
        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_())

【问题讨论】:

    标签: python pyqt pyqt5 pyside2


    【解决方案1】:

    改变这个:

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

    到这里:

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

    您正在尝试将回调返回的值绑定到clicked 信号,这是错误的。这也是程序启动后触发回调的原因,因为您要求在将它们传递给connect 之前对它们进行评估。

    您想将函数对象绑定到clicked 信号。

    【讨论】:

    • 哦,我真傻。现在我明白了,我正在调用这些函数,因为我没有将它们作为参数提供,而是在调用它们。谢谢!
    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    相关资源
    最近更新 更多