C++ 如何访问qt上的父小部件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/352758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:50:47  来源:igfitidea点击:

How to access to parent widget on qt?

c++linuxqtkde

提问by Giancarlo

I have an inherited QTreeWidget (called PackList) class and its parent is a KXmlGuiWindow. How can I access to the parent's slots?

我有一个继承的 QTreeWidget(称为 PackList)类,它的父类是 KXmlGuiWindow。我怎样才能访问父母的插槽?

I've tried getParent()->mySlot() from the QTreeWidget class but I've got

我已经尝试过 QTreeWidget 类中的 getParent()->mySlot() 但我有

error: no matching function for call to 'PackList::mySlot()'

Does anybody know the correct way? Thanks

有人知道正确的方法吗?谢谢

回答by Michael Bishop

If you know the parent's class, you will have to cast parentWidget() to that class and then call your slot. Keep in mind whether or not it's a slot makes no difference in this case. You are just calling a method.

如果您知道父类的类,则必须将 parentWidget() 转换为该类,然后调用您的插槽。请记住,在这种情况下,它是否是插槽没有区别。你只是在调用一个方法。

((KXmlGuiWindow*)parentWidget())->mySlot();

You can make the call without casting by wiring up your signal to the slot.

通过将信号连接到插槽,您可以在不进行投射的情况下拨打电话。

connect( this, SIGNAL(mySignal()), parentWidget(), SLOT(mySlot()) );

Lastly, you can use QMetaObject::invokeMethodto call it if you don't want to cast it. That's probably overkill.

最后,如果你不想转换它,你可以使用QMetaObject::invokeMethod来调用它。这可能是矫枉过正了。

回答by Jér?me

I'm not sure I fully understand your question.

我不确定我是否完全理解你的问题。

However, you can access the parent widget of a widget with parentWidget().

但是,您可以使用parentWidget()访问小部件的父小部件。

Then, you should be able to call any public slot :

然后,您应该能够调用任何公共插槽:

parentWidget()->a_slot();