开发者

How to run a loop using gui object names in qt?

I have a gui form, where multiple text boxes are present. I want to put their values inside an array. One way of doing it is by writing something like this

{array element } = ui->text_1->text();

and repeat it for text_2,text_3 upto n.

What I want is to run a loop and replace number portion of text box name in each cycle.

something like this {array element } = ui->text_{This number getting changed }->text();开发者_如何学JAVA

How can it be done in qt?


There are two ways of doing this.

  1. When you create the UI, instead of using text1, text2, etc. you create an array of QLineEdits (eg. std::vector<QLineEdit>) and then when you want to retrieve their values then simply iterate over this array

  2. Iterate over the children of the container widget. You can get the list of the children using the following (documentation):


   QList<QObject *> list = parentWidget->children();


Another option to those listed would be to create an array using an initializer list. Depending on how big the array is (and how often it changes), this might be workable.

QLineEdit* entries[] = { ui->text_0, ui->text_1, ui=>text_2 };
QStringList answers;
for ( int i = 0; i < 3; ++i )
{
    answers += entries[i]->text();
}


here is an expanded version of Matyas' solution:

class MyClass : public QWidget
{
   QStringList answers;
   void FillAnswersList(QObject *base)
   {
       QLineEdit *lineEdit = qobject_cast<QLineEdit>(base);
       if(lineEdit)answers.append(lineEdit->text());       
       else 
       {
           foreach(QObject *child, base->children())
              FillAnswersList(child);
       }
   }
};


If it is just the number changing, and always incrementing, there is another possible solution using QObject::findChild, which takes a name as a parameter.

QString name_template("text_%1");
QStringList answers;
for(int i = 0; i < MAX_TEXTS; ++i)
{
    QLineEdit *edit = ui->findChild<QLineEdit *>(name_template.arg(i));
    answers += edit->text();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜