首页 > 解决方案 > Python PyQt QPushButton 替换/覆盖方法

问题描述

我有这样的代码:

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

if self.added:

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

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

标签: pythonqtuser-interfacepyqtqpushbutton

解决方案


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

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

推荐阅读