使用...信号和插槽更改QActions的父级?

时间:2015-03-18 08:35:49

标签: python qt pyqt pyqt4 pyside

我有一堆QActions,其中一些是(目前)在两个子菜单和主菜单中。

正如您在下面的代码中所看到的,创建的操作没有父,因为操作与具有相同菜单的按钮共享。 那个插槽on_connect应该创建一个Wire类的实例。

阻止我创建一个wire类实例的唯一因素是jack_connector,它应该是按下并显示菜单的按钮。其他参数还可以,这是我唯一关心的时刻。 我发现我可以通过self.sender().parent().objectName()获得我需要的价值 但此时QActions的父集合,这就是为什么我需要设置在运行时将菜单显示为父级的按钮。

我已经知道可以使用.setParent()方法完成,但在按钮按下事件期间,我不知道如何对所有操作执行此操作。

这是最相关的代码:

scene = MyScene()
menu = QMenu()
widget_container = QWidget()

#dictonaries for dragbuttons (used later for connecting them)
jacks_dic = {}
inputs_dic = collections.OrderedDict()
wire_dic = {}

...
@pyqtSlot(str)
def on_connect(self,  input):
    print 'connected'
    jack_connector = self.sender().parent().objectName() #sender's parent of QAction should be the button
    wire_dic['wire_1'] = Wire(  jack_connector , widget_container.findChild( DragButton,  'btn_' + input ) , None, scene)

#Load Menu options for Jacks dragbuttons

#create sub-menus
submenus_dic = collections.OrderedDict()
submenus_dic['AIF1TX1_submenu'] = QMenu("AIF1TX1 (L) Record to Device")
submenus_dic['AIF1TX2_submenu'] = QMenu("AIF1TX2 (R) Record to Device")


actions_dic = collections.OrderedDict()
for input   in inputs_dic:
    #Create an Action
    actions_dic[ input  ] = QtGui.QAction( input, None)
    #TODO: Find a way to set parent a QAction after click
    #TODO: Research how to connect every action to a slot()
    actions_dic[ input ].triggered[()].connect( lambda input=input:  on_connect(actions_dic[ input  ], input)  )


    #Condition to add to a submenu
    if input[:-2] == 'AIF1TX1' :
        submenus_dic['AIF1TX1_submenu'].addAction( actions_dic[ input ] )

    if input[:-2] == 'AIF1TX2' :
        submenus_dic['AIF1TX2_submenu'].addAction( actions_dic[ input ] )

#Add SubMenus to Main Menu
for submenu in submenus_dic:
    menu.addMenu(submenus_dic[ submenu ] )

1 个答案:

答案 0 :(得分:0)

问题是正在触发一个操作,并且您正在尝试找出打开的菜单并激活该操作。您可以采取几种方法。

您可能希望使用QMenu的activeAction()方法探索QAction的menu(),parentWidget()和associatedWidgets()方法。您还可以查看可见的菜单。

QMenus创建一个小部件,表示向菜单添加操作时的操作。因此,您可以手动创建这些小部件并创建一组单独的触发器,以将另一个参数传递到您的函数中。

听起来你需要单独上课。

class MyMenu(QMenu):

    newWire = QtCore.Signal(str)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.wire_dic = collections.OrderedDictionary()

        self.action1 = QAction("text")
        self.action1.triggered.connect(self.action1method)
        self.addAction(self.action1)
    # end Constructor

    def action1method(self):
        # Maybe use self.windowTitle()
        self.wire_dic['wire_1'] = Wire(self.title(), widget_container.findChild( DragButton,  'btn_' + input ) , None, scene)
        self.newWire.emit("wire_1")
    # end action1method
# end class MyMenu

m1 = MyMenu("Menu1")
m2 = MyMenu("Menu2")

menubar.addMenu(m1)
menubar.addMenu(m2)

这样,每个对象都与它自己的操作相关联,而无需手动创建和管理一堆重复操作。这应该更容易管理,并且所有操作都将以相同的方式运行。