简体   繁体   English

QT中信号的未定义参考

[英]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). 我想在Qt中的单独文件中创建一个类,然后在我的主文件中使用此类(后台:辅助线程更新GUI)。 Thus I wrote ReadDPC.h -file: 于是我写了ReadDPC.h文件:

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: 在我的ReadDPC.cpp文件中:

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. read_DPC()是一个返回int值的函数,也放在cpp文件中。
But when I want to compile this, I get the error undefined reference to ReadDPC::currentCount(int) . 但是当我想编译它时,我得到了undefined reference to ReadDPC::currentCount(int)的错误undefined reference to ReadDPC::currentCount(int) Why? 为什么? How can I solve this? 我怎么解决这个问题?

Edit: Added Q_Object -Macro, no solution. 编辑:添加了Q_Object -Macro,没有解决方案。

Add Q_OBJECT macro to your subclass and run qmake. 将Q_OBJECT宏添加到子类并运行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. 如果没有这个宏,moc就无法创建信号,因此您会收到信号不存在的错误。

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 如果您对此感兴趣,请在此处阅读更多内容: 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. 当您打算使用Qt信号和插槽机制时,您必须在类的定义顶部添加Q_OBJECT宏,以便生成正确的moc_代码。

Why is this so? 为什么会这样?

The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions. 元对象编译器moc是处理Qt的C ++扩展的程序。

The moc tool reads a C++ header file. moc工具读取C ++头文件。 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. 如果它找到一个或多个包含Q_OBJECT宏的类声明,它将生成一个C ++源文件,其中包含这些类的元对象代码。 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 http://qt-project.org/doc/qt-4.8/moc.html#moc

  1. add Q_OBJECT 添加Q_OBJECT
  2. Clear your project 清除您的项目
  3. Run qmake 运行qmake
  4. And only after that, run your project 只有在那之后,运行你的项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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