1

I am trying to add property title into the main window of my application. But when I try to compile it, the compiler gives me this error:

mainwindow.cpp:19: undefined reference to `MainWindow::titleChanged(QString const&)'

I tried it on mingw and msvc2013 both fails on the same line with this error. The header/source files:

mainwindow.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);
    }
}

If I add the method below to the end of mainwindow.cpp file, then the application compiles and runs, but the signal isn't emitted:

void MainWindow::titleChanged(const QString&)
{
}

I tried to cleaning out the project's build folders, it doesn't help :(. I am using QT 5.4 and working on QT Creator.

mron
  • 95
  • 1
  • 8

1 Answers1

0

This question was already answered in comments by someone else. I just wanted to highlight the answer. The error in my case was in the header file

mainwindow.h:

class MainWindow : public QObject {
   QOBJECT_H  // This should be Q_OBJECT

...

I confused the QOBJECT_H macro used in QObject.h header file as an include guard with the Q_OBJECT macro used by QT's moc tool. Since the intellisense will offer you both options, they are easy to confuse.

I also got pointed to a good reading about common problems with signals/slots worth for reading: My signal / slot connection does not work

Community
  • 1
  • 1
mron
  • 95
  • 1
  • 8