Enumerate Children Push Buttons from a Window Handle
-
Hello,
I would like to enumerate the push buttons from a main window handle.
In the sample below (Win32 api FindWindow() to get the main window handle, just for testing but I will have to use it in the final application), the foreach loop gives : 1 QRubberBand instead of the 2 QPushButtons.
Why ?Thanks.
@
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QApplication>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QHBoxLayout>#include <Windows.h>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);QMainWindow *window = new QMainWindow();
window->setWindowTitle(QString::fromUtf8("Test QPushButtons"));
window->resize(500,300);QPushButton* button1 = new QPushButton("Button 1");
QPushButton* button2 = new QPushButton("Button 2");button1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
button2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);QWidget* centralWidget = new QWidget(window);
centralWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);QHBoxLayout* layout = new QHBoxLayout(centralWidget);
layout->addWidget(button1);
layout->addWidget(button2);window->setCentralWidget(centralWidget);
window->show();HWND hWnd = FindWindow(NULL, L"Test QPushButtons");
if (hWnd)
{
QWidget* widget = QWidget::find((WId)hWnd);QList<QWidget*> widgets = widget->findChildren<QWidget*>();
foreach (QWidget *widget, widgets)
{
widget->setStyleSheet("background-color:black;");
}
}return app.exec();
}
@ -
foreach works just fine. If you ask for all widgets, you get all widgets.
You are looking at the wrong place in may one line of sample code. Note that I have specified which type of children I am looking for (hint: look between < and >):
@
window->findChildren<QPushButton*>();or
widget->findChildren<QPushButton*>();
@