简体   繁体   中英

Undefined reference to signal in QT

I wanted to create a class in an separate file in Qt and then use this class in my main file (Background: Secondary thread updating GUI). Thus I wrote ReadDPC.h -file:

class ReadDPC: public QThread
{
//First edit:
Q_OBJECT
//End of first edit
public:
    void run();
signals:
    void currentCount(int);
};

And in my ReadDPC.cpp -file:

void ReadDPC::run()
{
    while(1)
    {
        usleep(50);
        int counts = read_DPC();
        emit currentCount(counts);
    }
}

read_DPC() is a function returning an int -value also placed in the cpp-file.
But when I want to compile this, I get the error undefined reference to ReadDPC::currentCount(int) . Why? How can I solve this?

Edit: Added Q_Object -Macro, no solution.

Add Q_OBJECT macro to your subclass and run qmake.

This macro allows you use signals and slots mechanism. Without this macro moc can't create your signal so you get error that your signal is not exist.

Code should be:

class ReadDPC: public QThread {
Q_OBJECT

Note that when you use new signal and slot syntax, you can get compile time error that you forgot add this macro. If it is interesting for you, read more here: http://qt-project.org/wiki/New_Signal_Slot_Syntax

When you are going to use Qt signals & slots mechanism you have to add Q_OBJECT macro in the top of definition of your class in order to generate correct moc_ code.

Why is this so?

The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.

The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.

http://qt-project.org/doc/qt-4.8/moc.html#moc

  1. add Q_OBJECT
  2. Clear your project
  3. Run qmake
  4. And only after that, run your project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM