转载自 https://blog.csdn.net/shangxiaqiusuo1/article/details/85253264
PyQt5 多窗口切换系列 一
-
# -*- coding: utf-8 -*-
-
'''
-
多窗口反复切换,只用PyQt5实现
-
'''
-
import sys
-
from PyQt5.QtWidgets
import QApplication, QMainWindow, QWidget, QPushButton
-
-
-
class FirstUi(QMainWindow):
-
def __init__(self):
-
super(FirstUi, self).__init__()
-
self.init_ui()
-
-
def init_ui(self):
-
self.resize(
300,
200)
-
self.setWindowTitle(
'First Ui')
-
self.btn = QPushButton(
'jump', self)
-
self.btn.setGeometry(
50,
100,
100,
50)
-
self.btn.clicked.connect(self.slot_btn_function)
-
-
def slot_btn_function(self):
-
self.hide()
-
self.s = SecondUi()
-
self.s.show()
-
-
-
class SecondUi(QWidget):
-
def __init__(self):
-
super(SecondUi, self).__init__()
-
self.init_ui()
-
-
def init_ui(self):
-
self.resize(
500,
350)
-
self.setWindowTitle(
'Second Ui')
-
self.btn = QPushButton(
'jump', self)
-
self.btn.setGeometry(
150,
150,
100,
50)
-
self.btn.clicked.connect(self.slot_btn_function)
-
-
def slot_btn_function(self):
-
self.hide()
-
self.f = FirstUi()
-
self.f.show()
-
-
-
def main():
-
app = QApplication(sys.argv)
-
w = FirstUi()
-
w.show()
-
sys.exit(app.exec_())
-
-
-
if __name__ ==
'__main__':
-
main()
注意,如果你发现你的多界面切换的时候出现闪退的情况,请注意,
-
def slot_btn_function(self):
-
self.hide()
-
self.s = SecondUi()
-
self.s.show()
上面的这个函数里面,打开第二个界面的时候,一定要在实例化对象的前面加上self,问题解决。
更新:新增用自定义信号和槽函数来打开第二个窗口,框架如下所示:其中要注意,自定义的信号要写在类的下面,而不要写进类里面的函数,不然会报错找不到connect。
-
# -*- coding: utf-8 -*-
-
-
import sys
-
from PyQt5.QtCore
import pyqtSignal
-
from PyQt5.QtWidgets
import QApplication, QMainWindow, QPushButton
-
-
-
class one(QMainWindow):
-
sig_1 = pyqtSignal()
-
-
def __init__(self):
-
super(one, self).__init__()
-
self.init_ui()
-
-
def init_ui(self):
-
self.resize(
300,
200)
-
self.setWindowTitle(
'1')
-
self.btn_1 = QPushButton(self)
-
self.btn_1.setText(
'Emit')
-
self.btn_1.setGeometry(
100,
80,
100,
40)
-
self.btn_1.clicked.connect(self.slot_btn_1)
-
self.sig_1.connect(self.sig_1_slot)
-
-
def slot_btn_1(self):
-
self.sig_1.emit()
-
-
def sig_1_slot(self):
-
self.t = two()
-
self.t.show()
-
-
-
class two(QMainWindow):
-
-
def __init__(self):
-
super(two, self).__init__()
-
self.resize(
500,
100)
-
self.setWindowTitle(
'two')
-
-
-
def ui_main():
-
app = QApplication(sys.argv)
-
w = one()
-
w.show()
-
sys.exit(app.exec_())
-
-
-
if __name__ ==
'__main__':
-
ui_main()