【问题标题】:Accessing aspects of QObject stored in QVector访问存储在 QVector 中的 QObject 的各个方面
【发布时间】:2016-12-15 19:19:55
【问题描述】:

我有一个 QObjects QVector<QWidget*> question_vector; 的 QVector。这些小部件是问题。 (我的申请就像一个问卷调查)。

创建问卷时,从组合框中的选项中选择问题类型,在 Questions 类中,问题被创建并存储在 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

SingleLineEdit 是widget,title,titleEdit,cmets,cmetsEdit。 如何访问,例如来自小部件的单个组件 cmetsText QLineEdit 的文本?

【问题讨论】:

  • 您已经问过类似的问题:stackoverflow.com/questions/41098139/… 并得到了答案。你的问题到底是什么?
  • 是的,有 line_edit_vector[index]->text();获取 QVector line_edit_vector 的文本;所以现在我继续前进并拥有 QVectorquestion_vector;由于添加了不同类型的小部件而不仅仅是 lineedits,所以如果我在 question_vector[3] 的对象中有一个 lineedit,我如何从中获取信息? question_vector[3]->cmetsText->text();不工作

标签: qt qobject qvector


【解决方案1】:

将元素转换为 QLineEdit:

QLineEdit *line_edit = dynamic_cast <QLineEdit *> (question_vector[3]);

if (line_edit)
{
   QString text = line_edit->text();
}

这是 C++ 编程的一个基本方面;您可能应该阅读 C++ 类,如何派生它们,如何使用基类指针和派生类指针等等。

【讨论】:

  • 您需要扩展您的 Question 类以提供对 QLineEdit 中包含的内容的访问。我提出的选角不正确;我误解了你的问题课是什么。由于 Question 封装了一堆小部件,因此您需要向 Question 添加方法,以便外部调用者可以获取文本:
【解决方案2】:

我想我已经设法解决了我想做的事情(至少部分)

所以我在这里

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);
}

我所做的是将QLineEdit *commentsText = new QLineEdit; 之类的内容更改为 section_commentsText = newLineEdit; - 在我的 question.h 中有 QTextEdit *section_commentsText

然后我就可以做到了

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多