2015-11-08 35 views
1

在Qt GUI中,我試圖用一個標籤連接一個TextEdit,這樣當用戶鍵入內容時,標籤會更新它的文本。以下是我已經試過:C + + Qt:連接帶標籤的文本編輯

void MainWindow ::updatelabel() 
{ 
    ui->label->setText("Hello"); 
} 

void MainWindow::changeTextColor() 
{ 
    QString textEdit = ui->textEdit->toPlainText(); 
    QString label = ui->label->text(); 
    connect(textEdit, SIGNAL(textChanged()), label, SLOT(updateLabel())); 
} 

這雖然給我一個錯誤:

error: no matching function for call to 'MainWindow::connect(QString&, const char*, QString&, const char*)' 
    connect(textEdit, SIGNAL(textChanged()), label, SLOT(updateLabel())); 
                     ^

什麼我做錯了,我該如何解決?謝謝!

回答

3

您的代碼中存在一些問題。下面是改變代碼註釋解釋它:

// make sure updateLabel is declared under slots: tag in .h file 
void MainWindow ::updatelabel() 
{ 
    // set label text to be the text in the text edit when this slot is called 
    ui->label->setText(ui->textEdit->toPlainText()); 
} 

// this is a very suspicious method. Where do you call it from? 
// I changed its name to better indicate what it does. 
void MainWindow::initializeUpdatingLabel() 
{ 
    //QString textEdit = ui->textEdit->toPlainText(); // not used 
    //QString label = ui->label->text(); // not used 

    // when ever textChanged is emitted, call our updatelabel slot 
    connect(ui->textEdit, SIGNAL(textChanged()), 
      this, SLOT(updatelabel())); // updateLabel or updatelabel??! 
} 

實用提示:當過您使用SIGNALSLOT宏,讓Qt Creator的自動完成它們。如果您手工輸入並輸入拼寫錯誤,則不會收到編譯時錯誤,而是會出現運行時警告信息,顯示沒有匹配的信號/插槽。

或者,假設你使用QT5和C++ 11能夠編譯器,你可以使用新的連接語法,它會給你編譯錯誤,如果你弄錯了。首先添加一行CONFIG += C++11.pro文件,然後再做連接這樣的:

void MainWindow::initializeUpdatingLabel() 
{ 
    connect(ui->textEdit, &QTextEdit::textChanged, 
      this, &MainWindow::updatelabel); 
} 

現在,如果你比如居然沒有updateLabel方法,你會得到編譯時錯誤,這比運行時消息好得多,你可能沒有注意到。你也可以用lambda替換整個updatelabel方法,但是這超出了這個問題/答案的範圍。

1

要連接到該方法中的錯誤textEditlabel變量:

- connect(textEdit, SIGNAL(textChanged()), label, SLOT(updateLabel())); 
+ connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(updateLabel())); 

一個QString不與信號和槽的Widget。您需要ui,ui->textEditthis的實際窗口小部件,當前類別包含updateLabel()

編輯:修復我犯的錯誤,因爲我在疲倦時回答。

+0

謝謝,這擺脫了錯誤。但新問題是,我想要做的事實際上並不奏效。如果我輸入內容,標籤的文字不會改變。你知道如何讓這個工作有任何機會嗎? –