C++ 你如何在 Qt 中获得小部件的孩子?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4311352/
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-28 15:05:35  来源:igfitidea点击:

How do you get a widget's children in Qt?

c++qtwidgetkeypressqtestlib

提问by Owen

I'm simulating keyPresses to an application through Qt's KeyPress function. All the KeyPresses work fine. However when I pass a QT::Key_Enterwhich is supposed to press the OK button of the currently active window, or QT::Key_Cancelfor the cancel button, it does nothing.

我正在通过 Qt 的 KeyPress 函数将 keyPresses 模拟到应用程序。所有的 KeyPresses 工作正常。但是,当我传递一个QT::Key_Enter应该按下当前活动窗口的确定按钮或QT::Key_Cancel取消按钮时,它什么也不做。

I'm thinking maybe, because these buttons don't have the focus, and the parent window itself has it. How do you get the children of a window? or rather find the OK or Cancel button on it so you could set it as the activeWindow and then pass KeyPresses successfully?

我在想,也许是因为这些按钮没有焦点,而父窗口本身有焦点。你如何得到一个窗口的孩子?或者更确切地说,在其上找到“确定”或“取消”按钮,以便将其设置为 activeWindow,然后成功传递 KeyPresses?

I have:

我有:

QWidget *pWin = QApplication::activeWindow;
QObjectList *pList = pWin->children();
//how do you iterate through the list and find the OK or Cancel button?

回答by Patrice Bernassola

You can use the findChildfunction with the object name to get a specific children. You can use too findChildrento get all children that have the same name and the iterate through the list using foreachor QListIterator.

您可以使用findChild带有对象名称的函数来获取特定的孩子。您可以使用太findChildren让具有相同的名称,并通过使用列表中的迭代所有的孩子foreachQListIterator

To get a button you can try:

要获得按钮,您可以尝试:

QPushButton* button = pWin->findChild<QPushButton*>("Button name");

回答by teukkam

You might want to put a custom event filteron your widget to capture the key event and see what really happens to it.

您可能希望在您的小部件上放置一个自定义事件过滤器来捕获关键事件并查看它到底发生了什么。