打印在PySide中单击的QMenu项目的文本

时间:2018-01-22 04:56:59

标签: python pyside

如何打印在pyside菜单中单击的菜单项的显示文本?

https://github.com/hantsy/spring-reactive-sample/tree/master/boot-data-mongo

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()

1 个答案:

答案 0 :(得分:1)

QMenutriggered信号,这会返回与所关注项目相关联的QAction,以获取我们使用text() 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())