Issue
How can i print the display text of the menu item clicked in a pyside menu?
import sys
import os
from PySide import QtGui, QtCore
from PySide import QtGui as QtWidgets
class MyTool(QtWidgets.QWidget):
def __init__(self,parent=None, path=None):
super(MyTool, self).__init__(parent)
self.resize(300,200)
# controls
self.ui_filters = QtGui.QToolButton()
self.ui_filters.setText('Filters ')
main_layout = QtWidgets.QVBoxLayout()
main_layout.addWidget(self.ui_filters)
self.setLayout(main_layout)
# actions
self.create_actions()
# properties
def create_actions(self):
# filters menu
self.menu_filters = QtWidgets.QMenu(self)
filters = ['Asphalt','Ceramic','Concrete','Fabric','Ground','Granite','Leather']
for x in filters:
action = self.menu_filters.addAction(x)
self.ui_filters.setMenu(self.menu_filters)
self.ui_filters.setPopupMode(QtWidgets.QToolButton.InstantPopup)
# Main
# -----------------------------------------------------------------------------
def main():
app = QtWidgets.QApplication(sys.argv)
ex = MyTool()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Solution
QMenu
has the triggered
signal, this returns the QAction
associated to the item pressed, to obtain the text we use the text()
method of the QAction
:
def create_actions(self):
# filters menu
self.menu_filters = QtWidgets.QMenu(self)
filters = ['Asphalt','Ceramic','Concrete','Fabric','Ground','Granite','Leather']
for x in filters:
action = self.menu_filters.addAction(x)
self.ui_filters.setMenu(self.menu_filters)
self.ui_filters.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.menu_filters.triggered.connect(self.onTriggered)
def onTriggered(self, action):
print(action.text())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.