Python PyQt QPushButton Replace/Overwrite 方法

Python PyQt QPushButton Replace/Overwrite Method

我有这样的代码:

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

if self.added:

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

但是当我点击登录按钮时,它会执行 self.add 然后 self.remove。有没有办法remove/overwriteself.add?谢谢

我不确定我对你的理解是什么,但请尝试下面的示例:

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