获取另一个类中对象的值

时间:2013-08-17 03:40:13

标签: qt

如何在另一个类中获取对象的值?比如我有2个类(类WidgetA和类WidgetB),这些类都是由类Widget创建的,如下所示:

//widget.h

#include <QWidget>
#include <QtGui>

class widgetA;
class widgetB;

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
private:
    QComboBox* comboBox;
    QStackedWidget* stackWidget;
    widgetA *wa;
    widgetB *wb;
};

class widgetA : public QWidget
{
    Q_OBJECT
public:
    widgetA(QWidget *parent = 0);
private:
    QString mystr;
    QLineEdit* lineEdit;
};

class widgetB : public QWidget
{
    Q_OBJECT

public:
    widgetB(QWidget *parent = 0);
    QLabel* label;
};

这是文件widget.cpp:

#include "widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    comboBox = new QComboBox(this);
    comboBox->addItem(tr("Widget A"));
    comboBox->addItem(tr("Widget B"));

    wa = new widgetA(this);
    wb = new widgetB(this);

    stackWidget = new QStackedWidget(this);
    stackWidget->addWidget(wa);
    stackWidget->addWidget(wb);
    stackWidget->setCurrentIndex(0);

    connect(comboBox, SIGNAL(currentIndexChanged(int)), stackWidget, SLOT(setCurrentIndex(int)));

    QVBoxLayout* layout = new QVBoxLayout;
    layout->addWidget(comboBox);
    layout->addWidget(stackWidget);

    setLayout(layout);
}

widgetA::widgetA(QWidget *parent):
    QWidget(parent)
{
    lineEdit = new QLineEdit;
    QHBoxLayout *lay = new QHBoxLayout;
    lay->addWidget(lineEdit);
    lineEdit->setReadOnly(true);

    setLayout(lay);
}


widgetB::widgetB(QWidget *parent):
    QWidget(parent)
{
    label = new QLabel("Hello QT");
    QHBoxLayout* lay = new QHBoxLayout;
    lay->addWidget(label);
    setLayout(lay);
}

如何在WidgetA类中将QLabel label的文本转换为WidgetA类中的QString mystr

1 个答案:

答案 0 :(得分:2)

在正确解耦和分离关注点方面最简洁的方法是添加一个getter forwarding label-&gt; text():

QString widgetB::text() const //or more specific name depending on the context
{
    return label->text();
}

如果您在值更改时需要通知,请添加信号:

class widgetB : public QWidget {
...
Q_SIGNALS:
    void textChanged(const QString& text);
...
};

并在更新标签时发出它。