Set widget style from a menu selection.
-
This code works for building the menu at startup. It creates a submenu for each style found.
@ styleNames = QStyleFactory.keys()
for style in styleNames:
self.actionStyle = QAction(self)
self.actionStyle.setObjectName("actionStyle")
self.menu_Styles.addAction(self.actionStyle)
self.menu_Preferences.addAction(self.menu_Styles.menuAction())
self.menubar.addAction(self.menu_File.menuAction())
self.menubar.addAction(self.menu_Preferences.menuAction())
self.actionStyle.setText(style)
self.actionStyle.triggered.connect(self.changeStyle))@This is the changeStyle function. The purpose is to change the widget style based on the menu selection.
@ def changeStyle(self, styleName):
QApplication.setStyle(QStyleFactory.create(styleName))@The menu gets created properly but I cannot figure out how to pass the styleName string to the function.
I've done a similar thing with a combobox which allowed me to pass the string with self.combobox.activated[str].connect(self.changeStyle). Similar syntax with 'triggered' does not work.
The app starts and the menu look great but when I select one of the menu options I get an error about the number of arguments.
bq. TypeError: changeStyle() takes exactly 2 arguments (1 given)
I am open to suggestions, advice, or comments.
Thanks in advance,
Cheers, -
I figured out how to pass two arguments to changeStyle function but no matter which menu item I select the same style gets passed.
QStyleFactory.keys() return "Cleanlooks" last and that is the style that get sent to changeStyle regardless of the menu selection.
Tried making sure each menu item had a separate name but it did not help.
@ styleNames = QtGui.QStyleFactory.keys()
for style in styleNames:
action = 'action' + style
self.action = QtGui.QAction(MainWindow)
self.action.setObjectName(style)
self.menu_Style.addAction(self.action)
self.menu_Preferences.addAction(self.menu_Style.menuAction())
self.menubar.addAction(self.menu_File.menuAction())
self.menubar.addAction(self.menu_Preferences.menuAction())
self.action.setText(style)
self.action.triggered.connect(lambda: self.changeStyle(self.action.text()))@Passing self.action.text() as the string argument to changeStyle but it's always the same.
Even though the text of the menu selection might be something like "Windows" or "CDE" the changeStyle function gets "Cleanlooks".
-
Found the solution "here":http://stackoverflow.com/questions/1100775/create-pyqt-menu-from-a-list-of-strings.
Change the triggered statement to "self.action.triggered.connect(lambda style=style self.changeStyle(self.action.text()))"