我有一个多窗口的PyQt5(Python 3.6.2和Qt 5.9.0(应用程序,它在标准桌面(即窗口管理(环境中运行时可以完美运行。我的目标平台是一个嵌入式设备(例如Raspberry Pi,i.MX6等(,我不会使用X11窗口系统。我目前正在使用 eglfs 平台测试嵌入式设备,该平台不支持多个窗口。我正在考虑使用QtWayland平台,或者修改我的方法,使用QtStackedWidget将"窗口"作为堆栈中的单个页面包含在内。
如何修改下面的高级窗口应用程序以利用 QStackedWidget 排列,以方便无窗口环境中的多页应用程序?
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from ui_Main import Ui_Main
from ui_Window1 import Ui_Window1
from ui_Window2 import Ui_Window2
class Main(QMainWindow, Ui_Main):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setupUi(self)
#Initialisation functions
self.PushButton1.clicked.connect(self.OpenWindow1)
self.PushButton2.clicked.connect(self.OpenWindow2)
def OpenWindow1(self):
showWindow1.show()
def OpenWindow2(self):
showWindow2.show()
class Window1(QMainWindow, Ui_Window1):
def __init__(self, parent=None):
super(Window1, self).__init__(parent)
self.setupUi(self)
class Window2(QMainWindow, Ui_Window2):
def __init__(self, parent=None):
super(Window2, self).__init__(parent)
self.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
showMain = Main()
showWindow1 = Window1()
showWindow2 = Window2()
showMain.show()
app.exec_()
我使用QStackedLayout将每个"窗口"嵌套在一个页面中,然后将外部.py文件的每个setupUI((函数合并到一个外部文件中。以下文件反映了这种方法,使用我的问题中发布的示例多窗口示例。
ui_Main.py:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Ui_Main(QtWidgets.QWidget):
def setupUi(self, Main):
Main.setObjectName("Main")
Main.resize(800, 480)
self.QtStack = QtWidgets.QStackedLayout()
self.stack1 = QtWidgets.QWidget()
self.stack2 = QtWidgets.QWidget()
self.stack3 = QtWidgets.QWidget()
self.Window1UI()
self.Window2UI()
self.Window3UI()
self.QtStack.addWidget(self.stack1)
self.QtStack.addWidget(self.stack2)
self.QtStack.addWidget(self.stack3)
def Window1UI(self):
self.stack1.resize(800, 480)
#PushButton1#
self.PushButton1 = QtWidgets.QPushButton(self.stack1)
self.PushButton1.setText("BUTTON 1")
self.PushButton1.setGeometry(QtCore.QRect(10, 10, 100, 100))
#PushButton2#
self.PushButton2 = QtWidgets.QPushButton(self.stack1)
self.PushButton2.setText("BUTTON 2")
self.PushButton2.setGeometry(QtCore.QRect(150, 150, 100, 100))
def Window2UI(self):
self.stack2.resize(800, 480)
self.stack2.setStyleSheet("background: red")
def Window3UI(self):
self.stack3.resize(800, 480)
self.stack3.setStyleSheet("background: blue")
Main.py:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
from ui_Main import Ui_Main
class Main(QMainWindow, Ui_Main):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setupUi(self)
self.PushButton1.clicked.connect(self.OpenWindow1)
self.PushButton2.clicked.connect(self.OpenWindow2)
def OpenWindow1(self):
self.QtStack.setCurrentIndex(1)
def OpenWindow2(self):
self.QtStack.setCurrentIndex(2)
if __name__ == '__main__':
app = QApplication(sys.argv)
showMain = Main()
sys.exit(app.exec_())