簡體   English   中英

C ++ Qt:使用標簽連接TextEdit

[英]C++ Qt: Connect a TextEdit with a Label

在Qt GUI中,我試圖將TextEdit與標簽連接起來,以便當用戶鍵入內容時,標簽會更新其文本。 這是我嘗試過的:

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()));
                                                                        ^

我在做什么錯,我該如何解決? 謝謝!

您的代碼中有一些問題。 這是更改后的代碼,並帶有解釋它的注釋:

// 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的編譯器,則可以使用新的connect語法,如果弄錯了,它將給您帶來編譯器錯誤。 首先在.pro文件中添加CONFIG += C++11行,然后執行如下連接:

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

現在,例如,如果您實際上沒有updateLabel方法,則會得到編譯時錯誤,這比您甚至可能沒有注意到的運行時消息好得多。 您也可以用lambda替換整個updatelabel方法,但這超出了此問題/答案的范圍。

您正在使用該方法連接到錯誤的textEditlabel變量:

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

QString不是帶有信號和插槽的窗口小部件。 你想從實際的小部件uiui->textEdit ,和this對包含當前類updateLabel()

編輯:修正我因疲倦而回答時犯的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM