Issue
I have a menu bar in PyQt5, whenever I press 'selection1', set of widgets should appear corresponding to selection1 and when I press 'selection2', a different set of widgets should appear corresponding to selection 2
Didnt found existing threads, and don't have a clue in implementing it.
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
selection1 = QAction('selection1', self)
selection1.triggered.connect(self.selection_1_widgets) # displays a set of widgets
menubar = self.menuBar()
fileMenu = menubar.addMenu('menu')
fileMenu.addAction(selection1)
fileMenu.addAction('selection2')
self.setGeometry(300, 300, 300, 200)
self.show()
def selection_1_widgets(self):
pass
def main():
app = QApplication(sys.argv)
ex = Main()
sys.exit(app.exec_())
Solution
If I understand you correctly, then pay attention to QStackedWidget
The QStackedWidget class provides a stack of widgets where only one widget is visible at a time.
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, QStackedWidget, \
QWidget, QHBoxLayout, QFormLayout, QLineEdit, QRadioButton, QLabel
from PyQt5.QtGui import QIcon
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.initUI()
hbox = QHBoxLayout(self.centralWidget)
hbox.addWidget(self.stack)
def initUI(self):
selection1 = QAction(QIcon("im.png"), 'selection1', self)
selection1.triggered.connect(self.selection_1_widgets)
selection2 = QAction(QIcon("Ok.png"), 'selection2', self)
selection2.triggered.connect(self.selection_2_widgets)
menubar = self.menuBar()
fileMenu = menubar.addMenu('menu')
fileMenu.addAction(selection1)
fileMenu.addAction(selection2)
self.stack1 = QWidget()
self.stack1Ui()
self.stack2 = QWidget()
self.stack2Ui()
self.stack = QStackedWidget(self)
self.stack.addWidget(self.stack1)
self.stack.addWidget(self.stack2)
def selection_1_widgets(self):
self.stack.setCurrentIndex(0)
def selection_2_widgets(self):
self.stack.setCurrentIndex(1)
def stack1Ui(self):
layout = QFormLayout()
layout.addRow("Name", QLineEdit())
layout.addRow("Address", QLineEdit())
self.stack1.setLayout(layout)
def stack2Ui(self):
layout = QFormLayout()
sex = QHBoxLayout()
sex.addWidget(QRadioButton("Male"))
sex.addWidget(QRadioButton("Female"))
layout.addRow(QLabel("Sex"),sex)
layout.addRow("Date of Birth",QLineEdit())
self.stack2.setLayout(layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Main()
ex.resize(300, 200)
ex.show()
sys.exit(app.exec_())
Answered By - S. Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.