在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()));
^
我做错了什么,我该如何解决?谢谢!
答案 0 :(得分: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??!
}
实用提示:当您使用SIGNAL
和SLOT
宏时,让Qt Creator自动填充它们。如果您手动输入它们并输入错误,则不会出现编译时错误,而是会出现关于没有匹配信号/插槽的运行时警告打印。
或者,假设您正在使用支持Qt5和C ++ 11的编译器,您可以使用新的连接语法,如果您弄错了,它将为您提供编译器错误。首先将行CONFIG += C++11
添加到.pro
文件,然后像这样进行连接:
void MainWindow::initializeUpdatingLabel()
{
connect(ui->textEdit, &QTextEdit::textChanged,
this, &MainWindow::updatelabel);
}
现在,如果您实际上没有updateLabel
方法,则会出现编译时错误,这比运行时消息要好得多,您可能甚至没有注意到。你也可以用lambda替换整个updatelabel
方法,但这超出了这个问题/答案的范围。
答案 1 :(得分:1)
您正在使用该方法连接错误的textEdit
和label
变量:
- connect(textEdit, SIGNAL(textChanged()), label, SLOT(updateLabel()));
+ connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(updateLabel()));
QString
不是带信号和插槽的小部件。您希望ui
,ui->textEdit
和this
的实际窗口小部件包含当前包含updateLabel()
的类。
编辑:修复我犯的错误,因为我累了回答。