【问题标题】:QT 5 connect() function to connect the textEditor and the MainWindowQT 5 connect() 函数连接 textEditor 和 MainWindow
【发布时间】:2015-09-28 11:22:35
【问题描述】:

我正在使用来自网络的一些示例代码学习 Qt 5,但我无法编译它。我有几个文件: 在 mainwindow.h 中,我有我的代码:

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    QTextEdit *textEdit;
};

类的实现在mainwindow.cpp中,为

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    setWindowTitle("TextPad [*]");
    textEdit = new QTextEdit(this);
    setCentralWidget(textEdit);
    connect(textEdit,&QTextEdit::textChanged,this,this->setWindowModified(true));
}

而在我的 main.cpp 中,它非常简单,就像

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow window;
    window.show();
    return app.exec();
}

如果我更改了 textEditor 中的文本,我想做的是在窗口标题中有一个“*”,所以我使用 connect() 函数。问题我无法正确编译,错误信息为

error: invalid use of void expression
     connect(textEdit,&QTextEdit::textChanged,this,this->setWindowModified(true));

感谢任何帮助!

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    改变

    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() 只需要信号/插槽的名称(使用单词SIGNALSLOT)或指向它的指针,使用函数指针样式,因此您不能将要执行的代码放在@ 987654327@电话。而是定义一个额外的插槽来实现所需的行为,如图所示。

    【讨论】:

    • 谢谢,我应用了你的第二种方法,它工作正常。您在代码中只有一个错字,但很容易通过编译找到。
    • @zhoudingjiang - 抱歉打错了。我目前无法访问 Qt,因此无法编译。现在修好了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多