前后端不分离的方式实现QMainWindow之间的跳转(不推荐)

在网上找了很久QMainWindow之间的跳转,找到的模板都是如下面这种的,但这种方式其实在用PyQt5进行界面编程时会非常麻烦,因为一般我们先利用QtDesinger生成*.ui文件,再用PyUIC工具转化得到对应的*.py文件,如果采用下面这种方式,每次都需要把修改后的界面代码粘贴过来。在界面复杂时,光是界面代码就已经多了,而且将前端代码和后端代码混合,不利于前后端分离,可能会引起很多问题。在找了很久之后,终于找到了最优的一种方法,特此记录下来。

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
################################################
#######创建主窗口
################################################
class FirstMainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('主界面')
 
        ###### 创建界面 ######
        self.centralwidget = QWidget()
        self.setCentralWidget(self.centralwidget)
        self.Layout = QVBoxLayout(self.centralwidget)
 
        # 设置顶部三个按钮
        self.topwidget = QWidget()
        self.Layout.addWidget(self.topwidget)
        self.buttonLayout = QHBoxLayout(self.topwidget)
 
        self.pushButton1 = QPushButton()
        self.pushButton1.setText("打开主界面")
        self.buttonLayout.addWidget(self.pushButton1)
 
        self.pushButton2 = QPushButton()
        self.pushButton2.setText("打开对话框")
        self.buttonLayout.addWidget(self.pushButton2)
 
        self.pushButton3 = QPushButton()
        self.pushButton3.setText("打开提示框")
        self.buttonLayout.addWidget(self.pushButton3)
 
 
 
        # 设置中间文本
        self.label = QLabel()
        self.label.setText("第一个主界面")
        self.label.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setFont(QFont("Roman times", 50, QFont.Bold))
        self.Layout.addWidget(self.label)
 
        # 设置状态栏
        self.statusBar().showMessage("当前用户:一心狮")
 
        # 窗口最大化
        self.showMaximized()
 
        ###### 三个按钮事件 ######
        self.pushButton1.clicked.connect(self.on_pushButton1_clicked)
        self.pushButton2.clicked.connect(self.on_pushButton2_clicked)
        self.pushButton3.clicked.connect(self.on_pushButton3_clicked)
 
 
 
 
    # 按钮一:打开主界面
    windowList = []
    def on_pushButton1_clicked(self):
        the_window =SecondWindow()
        self.windowList.append(the_window)   ##注:没有这句,是不打开另一个主界面的!
        self.close()
        the_window.show()
 
 
    # 按钮二:打开对话框
    def on_pushButton2_clicked(self):
        the_dialog = TestdemoDialog()
        if the_dialog.exec_() == QDialog.Accepted:
            pass
 
 
 
    # 按钮三:打开提示框
    def on_pushButton3_clicked(self):
        QMessageBox.information(self, "提示", "这是information框!")
        #QMessageBox.question(self, "提示", "这是question框!")
        #QMessageBox.warning(self, "提示", "这是warning框!")
        #QMessageBox.about(self, "提示", "这是about框!")
 
 
 
 
 
################################################
#######第二个主界面
################################################
class SecondWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('第二主界面')
 
        # 设置中间文本
        self.label = QLabel()
        self.label.setText("第二个主界面")
        self.label.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setFont(QFont("Roman times", 50, QFont.Bold))
        self.setCentralWidget(self.label)
 
        # 设置状态栏
        self.statusBar().showMessage("当前用户:一心狮")
 
        # 窗口最大化
        self.showMaximized()
 
 
 
    ###### 重写关闭事件,回到第一界面
    windowList = []
    def closeEvent(self, event):
        the_window = FirstMainWindow()
        self.windowList.append(the_window)  ##注:没有这句,是不打开另一个主界面的!
        the_window.show()
        event.accept()
 
 
 
 
################################################
#######对话框
################################################
class TestdemoDialog(QDialog):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('对话框')
 
        ### 设置对话框类型
        self.setWindowFlags(Qt.Tool)
 
 
 
 
 
################################################
#######程序入门
################################################
if __name__ == "__main__":
    app = QApplication(sys.argv)
    the_mainwindow = FirstMainWindow()
    the_mainwindow.show()
    sys.exit(app.exec_())

更好的方法实现QMainWindow之间的跳转(推荐)

首先利用QtDesigner和PyUIC工具得到前端代码并且创建界面对应的后端代码:

first_window.py: 第一个界面的前端代码

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'demo.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(558, 483)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(195, 186, 191, 51))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 558, 18))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "打开另一界面"))

对应的界面为:

Python pyqt选项卡切换 pyqt跳转界面_主界面跳转

another_window.py:第二个界面的前端代码

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'another_window.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(433, 413)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(170, 208, 181, 41))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(20)
        self.label.setFont(font)
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 433, 18))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "另一个界面"))

对应的界面为:

Python pyqt选项卡切换 pyqt跳转界面_主界面跳转_02

another_window_actions.py:第二个界面的后端代码

import sys
import another_window
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QFileDialog, QMessageBox
from PyQt5 import QtWidgets

class AnotherWindowActions(another_window.Ui_MainWindow, QMainWindow):

    def __init__(self):

        super(another_window.Ui_MainWindow, self).__init__()

        self.setupUi(self)

first_window_actions.py:第一个界面对应的话后端代码

import sys
import first_window
import another_window_actions
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QFileDialog, QMessageBox
from PyQt5 import QtWidgets

# 注意这里定义的第一个界面的后端代码类需要继承两个类
class FirstWindowActions(first_window.Ui_MainWindow, QMainWindow):

    def __init__(self):
		
        super(first_window.Ui_MainWindow, self).__init__()
        # 创建界面
        self.setupUi(self)

        self.pushButton.clicked.connect(self.open_btn_clicked)

    def open_btn_clicked(self):
        “”“
        	点击相应按钮,跳转到第二个界面
        ”“”
		# 实例化第二个界面的后端类,并对第二个界面进行显示
        self.another_window = another_window_actions.AnotherWindowActions()
        self.another_window.show()


if __name__ == '__main__':
	
    # 这里是界面的入口,在这里需要定义QApplication对象,之后界面跳转时不用再重新定义,只需要调用show()函数即可
    app = QApplication(sys.argv)
	
    # 显示创建的界面
    demo_window = FirstWindowActions()
    demo_window.show()

    sys.exit(app.exec_())

点击跳转后的结果为:

Python pyqt选项卡切换 pyqt跳转界面_QmainWindow_03