从 QGridLayout 获取 children - Qt

Get children from QGridLayout - Qt

我想从 mainLayout 中的所有 QTextEdit 获取文本。这是我的结构。

mainLayout = new QGridLayout( centralWidget );
mainLayout->setSpacing(0);
for(int mr = 0; mr < 3; mr++)//ustvarim 3 vrstice
{
    for(int mc = 0; mc < 3; mc++)//ustvarim 3 stolpce
    {
        QFrame * widget = new QFrame;
        widget->setFrameStyle(QFrame::Plain);
        widget->setFrameShape(QFrame::Box);

        QGridLayout * gridLayout = new QGridLayout(widget);
        gridLayout->setSpacing(0);
        gridLayout->setMargin(0);

        for(int r = 0; r < 3; r++)
        {
            for(int c = 0; c < 3; c++)
            {
                QTextEdit * tile = new QTextEdit("0");
                tile->setFrameStyle(QFrame::Plain);
                tile->setFrameShape(QFrame::Box);
                tile->setAlignment(Qt::AlignCenter);

                tile->setStyleSheet("font: 24pt ;");
                gridLayout->addWidget(tile, r, c, 1, 1, Qt::AlignCenter);
            }
        }
       mainLayout->addWidget(widget, mr, mc, 1, 1, Qt::AlignCenter);
    }
}

我是这样制作的,但是运行时崩溃了。我想我错过了 children 结构的东西。

for (int idx = 0; idx < mainLayout - > count(); idx++) {
    QFrame * item = dynamic_cast < QFrame * > (mainLayout - > itemAt(idx));
    for (int id = 0; id < item - > children().count(); id++) {
        QGridLayout * tile1 = dynamic_cast < QGridLayout * > (item - > children().at(id));
        QTextEdit * tile = dynamic_cast < QTextEdit * > (tile1 - > children().at(0));
        QString s = tile - > toPlainText();
        std::cout << s.toStdString() << std::endl;
    }
}

我的问题是,如何从这个结构中获取所有 QtextEdit 文本?

您无需深入研究布局。请尝试以下操作:

QList<QTextEdit*> textEdits = centralWidget->findChildren<QTextEdit *>()