[英]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! 在文件index.py中,此行工作正常,但在导入的类中,类似的行将不起作用! I can't understand why.
我不明白为什么。
Then i click pushButton by mice, it not work, no BtnClck1 method is called and no print-SecondWindowPrint. 然后我用鼠标单击pushButton,它不起作用,没有调用BtnClck1方法,也没有print-SecondWindowPrint。
But if i call PushButton click programmatically, it works fine. 但是,如果我以编程方式调用PushButton,则效果很好。
And PushButton works fine if i make connect from index.py 如果我从index.py建立连接,PushButton也可以正常工作
Here is full code on GitHub github.com/m0x3/test1 这是GitHub github.com/m0x3/test1上的完整代码
Here is code: 这是代码:
index.py import sys from PyQt5 import uic from PyQt5.QtWidgets import QMainWindow, QApplication 从PyQt5导入index.py sys从PyQt5导入uic.QtWidgets导入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 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. MainWindow.mn_general.pushButton_2调用form1.BtnClck1作为静态函数。 it's not clear but it works.
尚不清楚,但可以。 If it is good for you, you can define form1.BtnClck1 as static function:
如果对您有利,则可以将form1.BtnClck1定义为静态函数:
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. 另一种方法(更好的方法)是将form1类的实例放在MainWindow类的公共变量中。 You can change BtnClck function in Index.py like this:
您可以像这样在Index.py中更改BtnClck函数:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.