I am making an application, and at some point, the user will be creating some sort of from/survey. When creating, the user selects the various question types etc. by pressing a button and a new object will be created.
To create a new section, for example:
void CreateSurvey::question_section()
{
QLabel *sectionTitle = new QLabel();
sectionTitle->setText("New Section");
layout->addWidget(sectionTitle);
QLabel *titleLabel = new QLabel("Title");
QLineEdit *titleEdit = new QLineEdit("New Section");
QHBoxLayout *hLayout = new QHBoxLayout;
hLayout->addWidget(titleLabel);
hLayout->addWidget(titleEdit);
layout->addLayout(hLayout);
sectionCount++;
qDebug() << "sections: " << sectionCount;
}
When the application is running, the text 'TitleEdit' will be edited by the user for the title of the section. Say this has been called 3 times, so there are 3 sections. How do I get the strings entered for the title for each section?, or how do i get the string entered for a particular section?
Thanks
You can use a container like QVector
to store your QLineEdit
objects. Use this container to access the text of each QLineEdit
object.
#include <QApplication>
#include <QtWidgets>
class Survey : public QWidget
{
Q_OBJECT
public:
Survey(QWidget *parent = Q_NULLPTR) : QWidget(parent)
{
resize(600, 400);
setLayout(new QVBoxLayout);
layout()->setAlignment(Qt::AlignTop);
QPushButton *button = new QPushButton("Add line edit");
connect(button, &QPushButton::clicked, this, &Survey::addLineEdit);
layout()->addWidget(button);
QPushButton *print_button = new QPushButton("Print all text");
connect(print_button, &QPushButton::clicked, this, [=]
{
for(int i = 0; i < line_edit_vector.size(); i++)
qDebug() << getText(i);
});
layout()->addWidget(print_button);
}
QString getText(int index) const
{
if(line_edit_vector.size() > index)
return line_edit_vector[index]->text();
return QString();
}
private slots:
void addLineEdit()
{
QLineEdit *edit = new QLineEdit("Line edit");
layout()->addWidget(edit);
line_edit_vector.append(edit);
}
private:
QVector<QLineEdit*> line_edit_vector;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Survey survey;
survey.show();
return a.exec();
}
#include "main.moc"