C++ 使用Qt信号和插槽从另一个类更改标签文本

C++ 使用Qt信号和插槽从另一个类更改标签文本,c++,qt4,qt-creator,qt5,signals-slots,C++,Qt4,Qt Creator,Qt5,Signals Slots,我正在尝试从另一个类更改类标签的文本。我有一个类MainWindow,它包含标签 我还有一个Bot类,我想从中更改label的值 我试图创建信号和插槽,但我不知道从哪里开始 我创建了信号和插槽,如下所示: //in mainwindow.h signals: void changeTextSignal(); private slots: void changeText(); //in mainwindow.cpp void MainWindow::changeText(){ this->

我正在尝试从另一个类更改类标签的文本。我有一个类MainWindow,它包含标签

我还有一个Bot类,我想从中更改label的值

我试图创建信号和插槽,但我不知道从哪里开始

我创建了信号和插槽,如下所示:

//in mainwindow.h
signals:
void changeTextSignal();

private slots:
void changeText();

//in mainwindow.cpp
void MainWindow::changeText(){
this->label->setText("FooBar");
}
但我不知道如何连接信号,以便能够从另一个类更改标签的文本。

阅读Qt。如果我理解正确,您正试图从Bot向主窗口发出标签文本需要更改的信号。这是你怎么做的

//bot.h
class Bot
{
    Q_OBJECT;
    //other stuff here
signals:
    void textChanged(QString);
public:
    void someFunctionThatChangesText(const QString& newtext)
    {
        emit textChanged(newtext);
    }
}

//mainwindow.cpp
MainWindow::MainWindow
{
    //do other stuff
    this->label = new QLabel("Original Text");
    mybot = new Bot;   //mybot is a Bot* member of MainWindow in this example
    connect(mybot, SIGNAL(textChanged(QString)), this->label, SLOT(setText(QString)));
}

void MainWindow::hello()
{
    mybot->someFunctionThatChangesText("Hello World!");
}
阅读Qt。如果我理解正确,您正试图从Bot向主窗口发出标签文本需要更改的信号。这是你怎么做的

//bot.h
class Bot
{
    Q_OBJECT;
    //other stuff here
signals:
    void textChanged(QString);
public:
    void someFunctionThatChangesText(const QString& newtext)
    {
        emit textChanged(newtext);
    }
}

//mainwindow.cpp
MainWindow::MainWindow
{
    //do other stuff
    this->label = new QLabel("Original Text");
    mybot = new Bot;   //mybot is a Bot* member of MainWindow in this example
    connect(mybot, SIGNAL(textChanged(QString)), this->label, SLOT(setText(QString)));
}

void MainWindow::hello()
{
    mybot->someFunctionThatChangesText("Hello World!");
}

您应该阅读更多关于-add
QObject::connect(this,&MainWindow::changeTextSignal,this,&MainWindow::changeText)的内容
在MainWindow的目录中,您应该阅读更多关于-add
QObject::connect(this,&MainWindow::changeTextSignal,this,&MainWindow::changeText)的内容在主窗口的ctor中