您可以使用Qt的QStackedWidget类来实现这个功能。首先,您需要创建一个主窗口,并在其中添加一个QStackedWidget小部件。然后,为每个子窗口创建一个QWidget小部件,并将其添加到QStackedWidget中。
接下来,您需要为每个子窗口创建一个标题按钮。当用户单击按钮时,您可以使用setCurrentIndex()函数将QStackedWidget中当前显示的小部件更改为所选的小部件。
要布局子窗口,请使用布局管理器(例如QVBoxLayout或QHBoxLayout)在QWidget小部件中放置控件和小部件。如果您想像另一张图片布置它们,那么您可以使用QPixmap或QImage加载图像并将其放置在QWidget上。
以下是示例代码:
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QHBoxLayout, QWidget, QLabel, QStackedWidget
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Create a stacked widget
self.stacked_widget = QStackedWidget()
self.setCentralWidget(self.stacked_widget)
# Create child widgets
self.widget1 = QWidget()
layout1 = QVBoxLayout(self.widget1)
label1 = QLabel("This is widget 1")
layout1.addWidget(label1)
self.widget2 = QWidget()
layout2 = QHBoxLayout(self.widget2)
label2_1 = QLabel()
pixmap = QPixmap("path/to/image.png")
label2_1.setPixmap(pixmap)
label2_2 = QLabel("This is widget 2")
layout2.addWidget(label2_1)
layout2.addWidget(label2_2)
# Add child widgets to stacked widget
self.stacked_widget.addWidget(self.widget1)
self.stacked_widget.addWidget(self.widget2)
# Create buttons for switching between widgets
button1 = QPushButton("Widget 1")
button1.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(0))
button2 = QPushButton("Widget 2")
button2.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))
# Create a layout for the buttons and add them to the main window
button_layout = QHBoxLayout()
button_layout.addWidget(button1)
button_layout.addWidget(button2)
central_widget = QWidget()
# Set the layout for the central widget
layout = QVBoxLayout(central_widget)
# Add the stacked widget and the buttons to the central widget's layout
layout.addWidget(self.stacked_widget)
layout.addLayout(button_layout)
# Set the central widget of the main window
self.setCentralWidget(central_widget)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
这将创建一个具有两个子窗口的主窗口。第一个子窗口包含一个简单的标签,而第二个子窗口包含一个图像和另一个标签。您可以通过单击按钮在两个子窗口之间切换。