访问作为 GridLayout 成员的小部件

Accessing widgets which are members of a GridLayout

我是 Qt 开发新手(将近一个月),我在网上搜索了我的问题的解决方案,但一无所获。也许,我不知道如何或问什么。 所以,我现在将提出困扰我几天的问题。

我使用以下命令动态创建表单:

QWidget *window = new QWidget;

QGridLayout *headerlayout = new QGridLayout;
QGridLayout *bodylayout = new QGridLayout;
QGridLayout *layout = new QGridLayout;

QLabel *countrylabel = new QLabel;
QComboBox *countrycombo = new QComboBox;
country << "" << "England" << "Germany" << "Greece" << "Italy" << "Netherlands";
countrycombo->addItems(country);
countrylabel->setText("Χώρα");
connect(countrycombo, SIGNAL(currentIndexChanged(int)), this, SLOT(countryselected(int)));

//Suppose there 8 more widgets here        

headerlayout->addWidget(countrylabel,0,0);
headerlayout->addWidget(countrycombo,0,1);

//Here is the body part

QLabel *label0 = new QLabel;
QLabel *label1 = new QLabel;

label0->setText("LABEL1");
label1->setText("<b>LABEL2</b>");

//suppose there are 10 labels here and 8 more of the commands below.
bodylayout->addWidget(label0,0,0);
bodylayout->addWidget(label1,0,1);

//HERE IS the CLEVER PART

for (int i=1;i<9;i++){

        QComboBox *combo1 = new QComboBox;
        QSpinBox *spin1 = new QSpinBox;
        QSpinBox *spin2 = new QSpinBox;
        QSpinBox *spin3 = new QSpinBox;

        bodylayout->addWidget(combo1,i,0);
        bodylayout->addWidget(spin1,i,1);
        bodylayout->addWidget(spin2,i,2);
        bodylayout->addWidget(spin3,i,3);
        }

//END OF CLEVER PART

//Bring them all together            
layout->addLayout(headerlayout,1,10,0);  
layout->addLayout(bodylayout,10,10,0);
window->setLayout(layout);

使用这段代码,我创建了一个漂亮的动态表单,无需担心。 我的问题由以下问题描述:

-我如何访问 CLEVER 部分中的小部件以更改或读取它们的属性(例如组合框的当前索引、旋转框的值等)。 我想要做的是选择 countrycombo(在顶部),然后根据第一个组合值更改第二个组合的值(此处未描述,它在 headerlayout 中),然后更改值在 CLEVER 部分的组合框和 "read" 旋转框中的值,以便制作一些 SQL "magic".

我还阅读了有关 SIGNAL 和 SLOT 的内容,但问题仍然存在。 CLEVER 部分中的对象名称或地址。

我读到了有关创建 QList 的内容,但我不知道这是否是个好主意。

谢谢 尼克

您可以使用以下代码访问任何 QObject 实例:

QObject *object = parent->findChild<Class*>(objectName)

因此,您在代码中所要做的就是在创建小部件时定义一个对象名称。当你把它放到你的 QGridLayout 上时,它就成为它们的父级,所以你可以这样做:

countryCombo->setObjectName("Country");
...  
QComboBox *combo = headerLayout->findChild<QComboBox*>("Country");

或者您可以使用拥有您的布局的小部件 - 没关系。
另一种选择是当您使用插槽时,它在小部件发出信号时执行。如果你想访问 widget-sender,你可以使用下面的代码:

QComboBox *combo = qobject_cast<QComboBox*>(QObject::sender());