我正在编写一个包含两个不同部分的程序——我们称它们为 sub1 和 sub2。当我最初运行我的程序时,显示 sub1 并且我在后台加载 sub2 但不显示它。我在 sub1 中有一个菜单操作,可以让您切换到 sub2,而 sub2 中有一个菜单操作,可以让您切换回 sub1。我遇到的问题是尝试从 sub2 切换回 sub1 时。从 sub1 到 sub2 工作正常;sub1 被隐藏并显示 sub2。但是,当再次尝试显示 sub1 时,sub2 不会被隐藏。我是 PyQt 和 Python 的新手,所以我还不知道所有的错综复杂。所以,我使用的方法只是我通过反复试验得出的方法,绝不需要这样。简化代码如下。
#mass module
class MASS(PyQt5.QtWidgets.QMainWindow, massUi.Ui_MainWindow):
def __init__(self):
super(MASS, self).__init__()
self.actionSwitchToCompEval.triggered.connect(self.switchToCompEval)
def switchToCompEval(self):
massForm = main.massForm
massForm.hide()
compForm = main.compForm
compForm.show()
def showMass(self):
main(1)
def main(initiate=None):
if initiate == None:
main.app = PyQt5.QtWidgets.QApplication(sys.argv)
main.massForm = MASS()
main.compForm = CompEval.CompEval()
main.massForm.show()
main.app.exec_()
elif initiate == 1:
main.massForm = MASS()
main.compForm = CompEval.CompEval()
main.compForm.hide()
main.massForm.show()
elif initiate == 2:
pass
if __name__ == '__main__':
main()
#comp module
class CompEval(PyQt5.QtWidgets.QMainWindow, compEvalUi.Ui_MainWindow):
def __init__(self):
super(CompEval, self).__init__()
self.actionSwitchToMASS.triggered.connect(self.switchToMass)
def switchToMass(self):
mass.MASS().showMass()
def main():
form = CompEval()
form.show()
在 switchToCompEval 函数中,引用 main.massForm 和 main.compForm 变量似乎工作正常,但是当我尝试从 sub2(comp) 返回 sub1(mass) 时,我收到一个错误消息,该函数不包含该变量,这对我来说似乎很奇怪。我知道目前我如何进行此设置的几个方面很奇怪且远非理想,因此我们将不胜感激。谢谢。
因此,经过大量实验后,我确定解决此问题的最佳方法是将模块合二为一。如果您有多个 MainWindow 小部件并且需要能够在它们之间来回切换,请将访问这些小部件的类都保留在同一个模块中。
所以我有我的两个小部件类:
import PyQt5
import sys
#Below are the modules that are auto-generated when using Qt Designer to make an interface
import compWidget as compEvalUi
import massWidget as massUi
class MASS(PyQt5.QtWidgets.QMainWindow, massUi.Ui_MainWindow
def __init__(self):
super(MASS, self).__init__()
#setupUi function is in the auto-generated module and contains all the attributes of the interface
self.setupUi(self)
#menuSwitch is the name of the button/menu item that would need to be clicked
#in order to switch windows.
#The example shown here is if the action was attached to a menu-dropdown item
#which is why 'triggered' is used as opposed to 'clicked' if it were attached to a button
self.menuSwitch.triggered.connect(self.switchToCompWidget)
def switchToCompWidget(self):
INITIALIZE.massForm.hide()
INITIALIZE.compForm.show()
class CompEval(PyQt5.QtWidgets.QMainWindow, compEvalUi.Ui_MainWindow):
def __init__(self):
super(CompEval, self).__init__()
self.setupUi(self)
self.menuSwitch.triggered.connect(self.switchToMassWidget)
def switchToMassWidget(self):
INITIALIZE.compForm.hide()
INITIALIZE.massForm.show()
class INITIALIZE:
def __init__(self):
app = PyQt5.QtWidgets.QApplication(sys.argv)
INITIALIZE.massForm = MASS()
INITIALIZE.massForm.show()
INITIALIZE.compForm = CompEval()
app.exec_()
def main():
program = INITIALIZE()
if __name__ =='__main__':
main()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句