Search code examples
qtqobjectqvector

Accessing aspects of QObject stored in QVector


I have a QVector of QObjects QVector<QWidget*> question_vector;. These widgets are questions. (My application is like a questionnaire thing).

When creating a questionnaire, question types are chosen from the selection on a comboBox, and within Questions class, the question is created, and stored in the QVector.

void CreateSurvey::comboBox_selection(const QString &arg1)
{
    if(arg1 == "Single Line Text")
    {
    Question *singleLineText = new Question("Single Line Text");
    surveyLayout->addWidget(singleLineText);
    question_vector.append(singleLineText);
    qDebug() << "Number of items: "<< question_vector.size();

    } ...
}

void Question::create_singleLineEdit()
{
    QVBoxLayout *vLayout = new QVBoxLayout;
    QLabel *titleLabel = new QLabel("Title");
    vLayout->addWidget(titleLabel);
    QLineEdit *inputText = new QLineEdit;
    vLayout->addWidget(inputText);
    QLabel *commentsLabel = new QLabel("Comments");
    vLayout->addWidget(commentsLabel);
    QLineEdit *commentsText = new QLineEdit;
    vLayout->addWidget(commentsText);

    ui->frame->setLayout(vLayout);
}

This is what it looks like

The SingleLineEdit is the widget, the title, titleEdit, comments, commentsEdit. How do I access, for example the text from an individual component of the widget, the commentsText QLineEdit?


Solution

  • I think I've managed to solve what I was trying to do (at least partly)

    So I had here

    void Question::create_singleLineEdit()
    {
        QVBoxLayout *vLayout = new QVBoxLayout;
        QLabel *titleLabel = new QLabel("Title");
        vLayout->addWidget(titleLabel);
        QLineEdit *inputText = new QLineEdit;
        vLayout->addWidget(inputText);
        QLabel *commentsLabel = new QLabel("Comments");
        vLayout->addWidget(commentsLabel);
        QLineEdit *commentsText = new QLineEdit;
        vLayout->addWidget(commentsText);
        ui->frame->setLayout(vLayout);
    }
    

    What I did was changed stuff like QLineEdit *commentsText = new QLineEdit; to section_commentsText = newLineEdit; - Having QTextEdit *section_commentsText in my question.h.

    I was then able to do

    Question *object = question_vector[0];
    QString text = object->section_commentsText->text();
    qDebug() << text;