To create a main window using PySide6 with two actions that allow switching between two frames, you can use the following code. This code creates a simple application where clicking the actions in the menu bar will close the currently active frame and open the specified frame.
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QAction, QFrame, QVBoxLayout, QWidget
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("Main Window with Frames")
# Initialize frames
self.frame1 = QFrame(self)
self.frame1.setStyleSheet("background-color: lightblue;")
self.frame2 = QFrame(self)
self.frame2.setStyleSheet("background-color: lightgreen;")
# Set a layout for the main window
self.layout = QVBoxLayout()
self.container = QWidget()
self.container.setLayout(self.layout)
self.setCentralWidget(self.container)
# Initialize menu bar and actions
self.menu = self.menuBar().addMenu("Actions")
action1 = QAction("Open Frame 1", self)
action2 = QAction("Open Frame 2", self)
# Connect actions to methods
action1.triggered.connect(self.open_frame1)
action2.triggered.connect(self.open_frame2)
# Add actions to the menu
self.menu.addAction(action1)
self.menu.addAction(action2)
# Start by showing frame1
self.open_frame1()
def open_frame1(self):
self.close_active_frame()
self.layout.addWidget(self.frame1)
self.frame1.show()
def open_frame2(self):
self.close_active_frame()
self.layout.addWidget(self.frame2)
self.frame2.show()
def close_active_frame(self):
# Hide and remove all frames from the layout
items = (self.layout.itemAt(i) for i in range(self.layout.count()))
for item in items:
widget = item.widget()
if widget:
widget.hide()
self.layout.removeWidget(widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Explanation
-
Initialization:
- We create two QFrames
frame1 and frame2 with different background colors for visual distinction.
-
Layout:
- A
QVBoxLayout is used to hold and switch between the frames in the main window. This layout is set on a central widget.
-
Menu Actions:
- We create a menu with two actions: "Open Frame 1" and "Open Frame 2". These actions call the corresponding methods to switch frames.
-
Switching Frames:
open_frame1() and open_frame2() methods are used to show the specific frames by adding them to the layout.
close_active_frame() hides and removes the current widget from the layout, ensuring only one frame is visible at a time.
This code sets up a user interface with a simple menu-driven method to toggle between two frames within a main window.