你如何在 Qt 中获得一个小部件的孩子?

2022-01-18 00:00:00 keypress qt widget c++ qtestlib

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

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

我在想也许,因为这些按钮没有焦点,而父窗口本身有焦点.你如何得到一个窗口的孩子?还是找到它上面的 OK 或 Cancel 按钮,这样您就可以将其设置为 activeWindow,然后成功传递 KeyPresses?

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?

我有:

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

推荐答案

你可以使用 findChild() 函数使用对象名称来获取特定的孩子.

You can use the findChild() function with the object name to get a specific child.

您还可以使用 findChildren() 获取所有具有相同名称的孩子,然后使用 foreach()QListIterator.

You can also use findChildren() to get all the children that have the same name and then iterate through the list using foreach() or QListIterator.

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

To get a button you can try:

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

相关文章