如何从 QLineEdit 对象中检索文本

How to retrieve text from a QLineEdit object?

本文关键字:检索 文本 对象 QLineEdit      更新时间:2023-10-16

我有一个指向QLineEdit对象的指针数组,我想遍历它们并输出它们包含的文本。似乎我在指针方面遇到了麻烦。.

QList<QLineEdit *> boxes = ui->gridLayoutWidget->findChildren<QLineEdit *>();
for(QList<QLineEdit *>::iterator it = boxes.begin(); it != boxes.end(); it++)
{
    qDebug() << **it->text();  //not sure how to make this correct
}

我可以使用 qDebug 输出对象和名称,所以我知道 findChildren() 和迭代器设置正常,但我不确定如何获取文本。

尝试:

for(QList<QLineEdit *>::iterator it = boxes.begin(); it != boxes.end(); it++)
{
     qDebug() << (*it)->text();  
}

它与下面的代码相同,只需保存一个中间指针:

for(QList<QLineEdit *>::iterator it = boxes.begin(); it != boxes.end(); it++)
{
    QlineEdit* p= *it; // dereference iterator, get the stored element.
    qDebug() << p->text();
}

operator->的优先级高于operator*,请参阅C++运算符 wiki

为什么要使用迭代器?Qt有一个很好的foreach循环,可以为你做这些事情并简化语法:

QList<QLineEdit *> boxes = ui->gridLayoutWidget->findChildren<QLineEdit *>();
foreach(QLineEdit *box, boxes) {
    qDebug() << box->text();
}