Sekhmet
Sekhmet

Reputation: 533

Change label text from another class using Qt signals and slots

I'm trying to change text of a class Label from another class. I have class MainWindow, which contains Label.

I also have a Bot class from which I wanna change the value of label.

I'm trying to create signal and slots but I have no idea where to start.

I created signal and slots like so:

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

private slots:
void changeText();

//in mainwindow.cpp
void MainWindow::changeText(){
this->label->setText("FooBar");
}

But I have no idea how to connect a signal to be able to change Label's text from another class.

Upvotes: 1

Views: 5967

Answers (1)

Phlucious
Phlucious

Reputation: 3843

Read up on Qt signal-slot mechanism. If I understand you correctly, you are trying to signal from Bot to MainWindow that the Label text needs to change. Here's how you do it...

//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!");
}

Upvotes: 5

Related Questions