我刚开始使用PyQt5。我一直在尝试完成一个看似非常简单的任务,但没有获得足够的信息。经过大量的谷歌搜索,我已经能够关闭一个窗口,并在另一个UI加载时启动另一个窗口,但这不是我要在这里做的。
我想在同一窗口中切换UI。我正在将UI文件作为全局变量加载到我的python文件中,其中每个UI有2个类。当我单击一个UI中的特定按钮时,我想切换到同一窗口中的另一个UI。下面是代码示例:
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys from PyQt5.uic import loadUiType import os about_company_ui, _ = loadUiType(os.path.join('frontend', 'ui', 'about_company.ui')) intern_placement_ui, _ = loadUiType(os.path.join('frontend', 'ui', 'intern_placement.ui')) class InternPlacement(QMainWindow, intern_placement_ui): def __init__(self): QMainWindow.__init__(self) self.setupUi(self) self.intern_pushButton.clicked.connect(self.change) def change(self): self.about_company = AboutCompany() self.about_company.show() self.close() class AboutCompany(QMainWindow, about_company_ui): def __init__(self): QMainWindow.__init__(self) self.setupUi(self) if __name__ == '__main__': app = QApplication(sys.argv) window = InternPlacement() window.show() app.exec_()
您必须使用 QStackedWidget
QStackedWidget
import os import sys from PyQt5 import QtCore, QtGui, QtWidgets, uic ui_folder = os.path.join("frontend", "ui") about_company_ui, _ = uic.loadUiType(os.path.join(ui_folder, "about_company.ui")) intern_placement_ui, _ = uic.loadUiType(os.path.join(ui_folder, "intern_placement.ui")) class InternPlacement(QtWidgets.QMainWindow, intern_placement_ui): def __init__(self, parent=None): super(InternPlacement, self).__init__(parent) self.setupUi(self) class AboutCompany(QtWidgets.QMainWindow, about_company_ui): def __init__(self, parent=None): super(AboutCompany, self).__init__(parent) self.setupUi(self) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) intern_window = InternPlacement() about_window = AboutCompany() w = QtWidgets.QStackedWidget() w.addWidget(intern_window) w.addWidget(about_window) intern_window.intern_pushButton.clicked.connect(lambda: w.setCurrentIndex(1)) w.resize(640, 480) w.show() sys.exit(app.exec_())