Qt - 无法访问动态创建的QHBoxLayout小部件

3
在按下按钮时,我创建了一个QHBoxLayout,并向其中添加三个小部件(combobox和两个spinbox)。然后将创建的QHBoxLayout添加到在Qt Design视图中已经定义的垂直布局中。
在另一个方法中,我想访问每个已定义的QHBoxLayout并获取其每个combobox和spinbox的值。当迭代每个QHBoxLayout时,我能够看到每个布局内确实有3个“东西”(使用count()方法),但是我无法访问它们,并且在尝试查找布局的子项时始终得到空结果集。
//In the on click method I am doing the following

QHBoxLayout *newRow = new QHBoxLayout();

QComboBox *animCombo = new QComboBox();
QSpinBox *spinStart = new QSpinBox();
QSpinBox *spinEnd = new QSpinBox();

newRow->addWidget(animCombo);
newRow->addWidget(spinStart);
newRow->addWidget(spinEnd);

ui->animLayout->addLayout(newRow); //animLayout is a vert layout


//in another method, I want to get the values of the widgets in the horiz layouts

foreach( QHBoxLayout *row, horizLayouts ) {

  qDebug() << row->count(); //outputs 3 for each of the QHBoxLayouts

}

任何帮助都非常感激,谢谢!
1个回答

1
您可以使用以下函数:

QLayoutItem * QLayout::itemAt(int index) const [纯虚函数]

因此,我会编写类似于以下内容的代码:
for (int i = 0; i < row.count(); ++i) {
    QWidget *layoutWidget = row.itemAt(i))->widget();
    QSpinBox *spinBox = qobject_cast<QSpinBox*>(layoutWidget);
    if (spinBox)
        qDebug() << "Spinbox value:" << spinBox->value();
    else
        qDebug() << "Combobox value:" << (qobject_cast<QComboBox*>(layoutWidget))->currentText();
}

免责声明:这只是伪代码,用于表达思想。


太棒了。谢谢,非常感激! - mumush

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接