2013-07-25 36 views
-1

我試圖從另一個類更改一個類的標籤文本。我有類MainWindow,其中包含標籤。使用Qt信號和插槽更改另一個類的標籤文本

我也有一個Bot類,我想從中改變標籤的價值。

我試圖創建信號和插槽,但我不知道從哪裏開始。

我創建的信號和插槽,像這樣:

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

private slots: 
void changeText(); 

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

但我不知道如何連接的信號,以便能夠標籤的文本從另一個類改變。

+0

你應該多讀一點有關[信號插槽機制(http://qt-project.org/doc/qt-5.0/qtcore/signalsandslots .html) - 添加'QObject :: connect(this,&MainWindow :: changeTextSignal,this,&MainWindow :: changeText);'在MainWindow的ctor –

回答

4

請閱讀Qt signal-slot mechanism。如果我正確地理解了你,你試圖從Bot發信號給MainWindow,標籤文本需要改變。這裏是你如何做到這一點...

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