信号上的QT未定义参考编译错误
QT undefined reference compilation error on a signal
我正在尝试将属性标题添加到应用程序的主窗口中。但当我试图编译它时,编译器会给我这个错误:
mainwindow.cpp:19: undefined reference to `MainWindow::titleChanged(QString const&)'
我在mingw和msvc2013上尝试过,但都在同一行失败,出现了这个错误。头文件/源文件:
主窗口.h:
#ifndef MAINWINDOW
#define MAINWINDOW
#include <QObject>
#include <QString>
class MainWindow : public QObject {
QOBJECT_H
Q_PROPERTY(QString title READ getTitle WRITE setTitle NOTIFY titleChanged)
public:
MainWindow();
QString getTitle();
public slots:
void setTitle(const QString& title);
signals:
void titleChanged(const QString& title);
private:
QString title_;
};
#endif // MAINWINDOW
mainwindow.cpp:
#include "mainwindow.h"
#include <QString>
MainWindow::MainWindow()
{
}
QString MainWindow::getTitle()
{
return title_;
}
void MainWindow::setTitle(const QString& title)
{
if (title_ != title) {
title_ = title;
emit titleChanged(title);
}
}
如果我将下面的方法添加到mainwindow.cpp文件的末尾,那么应用程序就会编译并运行,但不会发出信号:
void MainWindow::titleChanged(const QString&)
{
}
我试图清理项目的构建文件夹,但没有帮助:(.我正在使用QT 5.4并使用QT Creator。
其他人已经在评论中回答了这个问题。我只是想强调一下答案。在我的案例中,错误出现在头文件中
主窗口.h:
class MainWindow : public QObject {
QOBJECT_H // This should be Q_OBJECT
...
我混淆了QOBJECT.H头文件中用作包含保护的QOBJECT_H宏与QT的moc工具使用的Q_OBJECT宏。由于intellisense将为您提供这两种选择,因此它们很容易混淆。
我还读了一篇关于信号/插槽常见问题的好文章,值得一读:我的信号/插槽连接不起作用