我正在编写一个包含两个不同部分的程序-我们将其称为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)时出现错误,该函数没有包含该变量,这对我来说似乎很奇怪。我知道目前如何进行此设置的几个方面很奇怪,远非理想,因此任何建议都将不胜感激。谢谢。
答案 0 :(得分:0)
因此,经过大量的实验,我确定针对此问题的最佳解决方案是将模块组合为一个。如果您有多个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()
答案 1 :(得分:0)
您可以使用信号和插槽来分隔逻辑,而不必在类之间共享全局参数。