C++ Qt-如何找到合适的孩子

C++ Qt-如何找到合适的孩子,c++,qt,C++,Qt,我试图找到一个我添加到屏幕上的小部件,并对其进行一些操作,但每次子项列表都是空的。我做错了什么? 以下是代码(要运行它,请创建一个新的干净项目并替换MainWindow.cpp中的文本): #包括“mainwindow.h” #包括“ui_main window.h” #包括 #包括 #包括 #包括 主窗口::主窗口(QWidget*父窗口) :QMainWindow(父级) ,ui(新ui::Main窗口) { 用户界面->设置用户界面(此); QLabel*wid=新的QLabel(“你好”

我试图找到一个我添加到屏幕上的小部件,并对其进行一些操作,但每次子项列表都是空的。我做错了什么? 以下是代码(要运行它,请创建一个新的干净项目并替换MainWindow.cpp中的文本):

#包括“mainwindow.h”
#包括“ui_main window.h”
#包括
#包括
#包括
#包括
主窗口::主窗口(QWidget*父窗口)
:QMainWindow(父级)
,ui(新ui::Main窗口)
{
用户界面->设置用户界面(此);
QLabel*wid=新的QLabel(“你好”);
ui->centralWidget->layout()->addWidget(wid);
QList list=ui->centralWidget->findChildren();

qDebug()您使小部件成为布局的子项而不是
ui->centralWidget
@drescherjm,也就是说,对于布局,这不起作用?尽管查看文档,默认参数是进行递归查找。我希望布局是
ui->centralWidget
的子项,但不确定为什么失败。@drescherjm如果我写
>QList list=ui->centralWidget->layout()->findChildren();
,这也不起作用,也许addWidget()并没有使它成为布局的子项。我想是这样的。你可以使用构造函数的父参数来解决这个问题。我的意思是
QLabel*wid=new QLabel(“hello”,ui->centralWidget);
应该使原始示例起作用。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QLabel>
#include <QLayout>
#include <QList>

MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QLabel* wid = new QLabel("hello");
    ui->centralWidget->layout()->addWidget(wid);
    QList<QLabel*> list = ui->centralWidget->findChildren<QLabel*>();
    qDebug() << list.isEmpty();
}

MainWindow::~MainWindow()
{
    delete ui;
}