Python PyQt QPushButton替换/覆盖方法

时间:2019-02-06 10:36:53

标签: python qt user-interface pyqt qpushbutton

我有这样的代码:

self.addBtn.clicked.connect(self.add)

if self.added:

    self.addBtn.clicked.connect(self.remove)

但是,当我单击登录按钮时,它先执行self.add,然后执行self.remove。有没有办法删除/覆盖self.add?谢谢

1 个答案:

答案 0 :(得分:0)

我不确定您需要做什么,但请尝试以下示例:

import sys
from PyQt5.QtWidgets import (QPushButton, QVBoxLayout, QApplication, 
                             QWidget, QLabel)

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

        self.flag = True

        self.label  = QLabel()
        self.addBtn = QPushButton("add") 
        self.addBtn.clicked.connect(self.add_remove)        

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.label)
        vbox.addWidget(self.addBtn)

    def add_remove(self):
        if self.flag:
            print("You clicked the button: `add`")
            self.flag = False
            self.addBtn.setText("remove")
            # Do something ...
            self.label.setText("Hello Tom Rowbotham")
        else:
            print("You clicked the button: `remove`")
            self.flag = True
            self.addBtn.setText("add")
            # Do something ...       
            self.label.setText("")            


if __name__ == '__main__':
    app  = QApplication(sys.argv)
    w = Test()
    w.show()
    sys.exit(app.exec_())