在两个QWidget实例之间共享数据

时间:2016-01-02 05:34:07

标签: c++ qt qwidget

我想在两个QWidget实例之间共享一个字符串。

enter image description here

在main.cpp中,实例化了两个对象,如下所示:

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])

{

QApplication a(argc, argv);

Dialog w1,w2; //Derived from QWidget

w1.show();

w2.show();

return a.exec();
}

1 个答案:

答案 0 :(得分:2)

我将介绍SharedState类:

// shared_state.h
#ifndef SHARED_STATE_HPP
#define SHARED_STATE_HPP

#include <QObject>

class SharedState : public QObject
{
    Q_OBJECT
public:

    SharedState(QString initialValue = "")
        : currentValue(initialValue)
    {}

    QString getCurrentValue()
    {
         return currentValue;
    }

public slots:
    void setValue(QString newValue)
    {
        if(currentValue != newValue)
        {
            currentValue = newValue;
            emit valueChanged(currentValue);
        }
    }

signals:
    void valueChanged(QString);

private:
    QString currentValue;
};

#endif // SHARED_STATE_HPP

现在我将在Dialog的构造函数中提供对SharedState的引用,

// dialog.h
#ifndef DIALOG_H
#define DIALOG_H

#include <QWidget>
#include "shared_state.h"

namespace Ui {
class Dialog;
}

class Dialog : public QWidget
{
    Q_OBJECT

public:
    explicit Dialog(SharedState& state, QWidget *parent = 0);
    ~Dialog();

private slots:
    void handleTextEdited(const QString&);

public slots:
    void handleInternalStateChanged(QString);

private:
    Ui::Dialog *ui;

    SharedState& state;
};

#endif // DIALOG_H

您可能已经注意到我添加了两个插槽,一个用于处理手动编辑文本时的情况,另一个用于处理共享状态将告知我们已过期的插槽。

现在在Dialog的构造函数中,我必须将初始值设置为textEdit,并将信号连接到插槽。

// dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(SharedState& state, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Dialog),
    state(state)
{
    ui->setupUi(this);
    ui->textEdit->setText(state.getCurrentValue());

    QObject::connect(ui->textEdit, SIGNAL(textEdited(QString)),
             this, SLOT(handleTextEdited(QString)));
    QObject::connect(&state, SIGNAL(valueChanged(QString)),
             this, SLOT(handleInternalStateChanged(QString)));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::handleTextEdited(const QString& newText)
{
    state.setValue(newText);
}

void Dialog::handleInternalStateChanged(QString newState)
{
    ui->textEdit->setText(newState);
}

现在main功能的变化:

// main.cpp
#include "dialog.h"
#include "shared_state.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    SharedState state("Initial Value");
    Dialog w1(state), w2(state);
    w1.show();
    w2.show();

    return a.exec();
}