QT 5 connect()函数连接textEditor和MainWindow [英] QT 5 connect() function to connect the textEditor and the MainWindow
问题描述
我正在学习Qt 5的一些示例代码从web,但我不能编译它。我有几个文件:
在mainwindow.h,我有我的代码:
I am learning Qt 5 with some example code from web, but I cannot compile it. I have several files as: in mainwindow.h, I have my code:
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
QTextEdit *textEdit;
};
类的实现在mainwindow.cpp中,如
The implementation of the class is in mainwindow.cpp, as
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
setWindowTitle("TextPad [*]");
textEdit = new QTextEdit(this);
setCentralWidget(textEdit);
connect(textEdit,&QTextEdit::textChanged,this,this->setWindowModified(true));
}
在我的main.cpp中,它很简单,因为
And in my main.cpp, it is quite simple, as
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
我想要做的是在窗口标题中有一个* ,如果我改变了textEditor中的文本,所以我使用一个connect()函数。问题我无法正确编译,错误消息是
What I want to do is the have a "*" in the window title, if I have changed the text in the textEditor, so I use a connect() function. The problem I cannot compile it correctly, the error message is as
error: invalid use of void expression
connect(textEdit,&QTextEdit::textChanged,this,this->setWindowModified(true));
任何帮助都非常感谢!
推荐答案
更改
connect(textEdit,&QTextEdit::textChanged,this,this->setWindowModified(true));
到
connect(textEdit,SIGNAL(textChanged()),this,SLOT(myTextChanged()));
//or you can use alternate form
connect(textEdit,&QTextEdit::textChanged,this,myTextChanged);
并定义槽位
void MainWindow::myTextChanged() {
setWindowModified(true);
}
connect只需要信号/槽的名称(使用字
SIGNAL
和 SLOT
)或指向它的指针,使用函数指针样式,因此您不能将代码放置在 connect()
调用中执行。而是定义一个额外的插槽来实现所需的行为,如下所示。
connect()
requires only either the name of the signal/slot (using the words SIGNAL
and SLOT
) or a pointer to it, using the function pointer style, so you cannot place code to execute in a connect()
call. Instead define an extra slot to implement the desired behavior, as shown.
这篇关于QT 5 connect()函数连接textEditor和MainWindow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!