gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:14:09 24 4
gpt4 key购买 nike

我想在两个 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();
}

最佳答案

我会介绍 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();
}

关于c++ - 在两个 QWidget 实例之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com