简体   繁体   中英

PyQt5 button click not work in imported class

In file index.py this line works fine, but in imported class similar line won't work! I can't understand why.

Then i click pushButton by mice, it not work, no BtnClck1 method is called and no print-SecondWindowPrint.

But if i call PushButton click programmatically, it works fine.

And PushButton works fine if i make connect from index.py

Here is full code on GitHub github.com/m0x3/test1

Here is code:

index.py import sys from PyQt5 import uic from PyQt5.QtWidgets import QMainWindow, QApplication

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Set up the MainWindow from Designer.
        uic.loadUi("mw.ui", self)

        # Connect up the buttons.
        self.pushButton.clicked.connect(self.BtnClck)

        self.show()

    def BtnClck(self):
        # Set up the ContentWindow from Designer.
        from form1 import form1
        form1(self.mn_general)
        self.mn_general.pushButton_2.clicked.connect(form1.BtnClck1) #this works fine

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()
    sys.exit(app.exec_())

form1.py

from PyQt5 import uic

class form1:
    def __init__(self, obj):
        super().__init__()
        uic.loadUi("form1.ui", obj)

        obj.pushButton.setText('TextChanged on init') #this works fine
        obj.pushButton.clicked.connect(self.BtnClck1) #this NOT works
        obj.pushButton.click() #this works fine!

    def BtnClck1(self):
        print('SecondWindowPrint')

MainWindow.mn_general.pushButton_2 calls form1.BtnClck1 as a static function. it's not clear but it works. If it is good for you, you can define form1.BtnClck1 as static function:

class form1:
def __init__(self, obj):
    ...........

@staticmethod
def BtnClck1():
    print('SecondWindowPrint')

Another way (better way) is put instance of form1 class in a public variable in MainWindow class. You can change BtnClck function in Index.py like this:

    def BtnClck(self):
    # Set up the ContentWindow from Designer.
    from form1 import form1
    self.Form=form1(self.mn_general,5)
    self.mn_general.pushButton_2.clicked.connect(form1.BtnClck1) #this works fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM