![46da3ac51961222590850279b081d586.png](https://i-blog.csdnimg.cn/blog_migrate/263b8558171e75673c2bcb37cdcc4932.jpeg)
最近在用pyqt5做界面,需要进行多页面的跳转。在csdn上搜索了一些答案,一个最多浏览的答案居然是用隐藏页面(self.hide)这种掩耳盗铃的方法,看似实现了页面跳转,但实际上终端有好几个QMainWindow在同时运行,实在是误人子弟。下面贴上我在GitHub上找到的一个个人认为思路比较巧妙的解决办法。
https://gist.github.com/MalloyDelacroix/2c509d6bcad35c7e35b1851dfc32d161gist.github.com下面贴上我对代码的一些注释。
这个方法的巧妙之处在于创建了一个控制类controller,第一是将不同的界面作为controller的属性(self.page1, self.page2 ...),第二用于接收每个界面发出的信号,从而在更高的层面对页面变化进行统筹调动。在希望实现跳转界面的按钮上添加可以发射信号的函数(pyqtSignal.emit),并且在controller类中定义接收函数5(pyqtSignal.connect),在函数中创建新的界面,用close()和show()来控制页面的跳转的顺序。
import sys
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QWidget):
switch_window = QtCore.pyqtSignal(str)
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setWindowTitle('Main Window')
layout = QtWidgets.QGridLayout()
self.line_edit = QtWidgets.QLineEdit()
layout.addWidget(self.line_edit)
self.button = QtWidgets.QPushButton('Switch Window')
self.button.clicked.connect(self.switch)
layout.addWidget(self.button)
self.setLayout(layout)
def switch(self):
self.switch_window.emit(self.line_edit.text())
class WindowTwo(QtWidgets.QWidget):
def __init__(self, text):
QtWidgets.QWidget.__init__(self)
self.setWindowTitle('Window Two')
layout = QtWidgets.QGridLayout()
self.label = QtWidgets.QLabel(text)
layout.addWidget(self.label)
self.button = QtWidgets.QPushButton('Close')
self.button.clicked.connect(self.close)
layout.addWidget(self.button)
self.setLayout(layout)
class Login(QtWidgets.QWidget):
switch_window = QtCore.pyqtSignal()
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setWindowTitle('Login')
layout = QtWidgets.QGridLayout()
self.button = QtWidgets.QPushButton('Login')
self.button.clicked.connect(self.login)
layout.addWidget(self.button)
self.setLayout(layout)
def login(self):
self.switch_window.emit()
class Controller:
def __init__(self):
pass
def show_login(self):
self.login = Login()
self.login.switch_window.connect(self.show_main)
self.login.show()
def show_main(self):
self.window = MainWindow()
self.window.switch_window.connect(self.show_window_two)
self.login.close()
self.window.show()
def show_window_two(self, text):
self.window_two = WindowTwo(text)
self.window.close()
self.window_two.show()
def main():
app = QtWidgets.QApplication(sys.argv)
controller = Controller()
controller.show_login()
sys.exit(app.exec_())
if __name__ == '__main__':
main()