zoukankan      html  css  js  c++  java
  • 非Qt工程使用Qt的信号槽机制

    非Qt工程,使用Qt的信号槽机制,蛋疼不?反正我现在就是要做这样一件蛋疼的事。

    要使用Qt的信号槽机制,下面是从Qt Assist里面关于 signal & slots 的一句介绍:

    All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject.

    翻译过来就是:所有包含信号与槽的类,必须引用 Q_OBJECT这个宏,然后需要从QObject继承过来。

    这样得到我们要做事情的前2个步骤: 
    1. 从QObject继承。 
    2. 类中引用 Q_OBJECT这个宏。 
    我打算在A类里面发出一个信号,然后让B类接收。

    //A.h的内容
    #pragma once
    
    #include <QtCore/QObject>
    
    class A :public QObject
    {
        Q_OBJECT
    public:
        void sendA() { emit signalA(999);}
    signals:
        void signalA(int);
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    //B.h 的内容
    #pragma once
    #include <QtCoreQObject>
    
    class B : public QObject
    {
        Q_OBJECT
    public:
        B() : _receiveData(0)
        {
    
        }
    public slots:
            void receiveA(int v)
            {
                _receiveData = v;
            }
    public:
        int _receiveData;
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    做完这两件事情之后,编译不通过啊,怎么办?关于头文件,LIB文件的包含,这里不讲了。 
    这里引用到了QtCore/QObject这个头文件, Qt5Cored.lib(根据版本不同,名称不一样)这个库。

    1. 由于Q_OBJECT这个宏是由moc来处理的,还需要使用moc对我们的头文件进行编译。由于不是Qt工程,所以这个编译需要手动设置一下,具体参考下面 
      http://blog.csdn.net/xiaofengkuang/article/details/9999147 
      使用moc编译完了之后,然后再讲moc_A.cpp, moc_B.cpp添加到工程中来即可。

    测试代码:

    #include "A.h"
    #include "B.h"
    #include <assert.h>
    
    #include <QtCore/QObject>
    
    int main(int argc, char **argv)
    {
        A a;
        B b;
        QObject::connect(&a, SIGNAL(signalA(int)), &b, SLOT(receiveA(int)));
        a.sendA();
        int data = b._receiveData;
        assert(data == 999);
        return 0;
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    测试通过。

    所以,总结一下非Qt工程,使用Qt的信号槽的步骤: 
    1. 继承自QObject 
    2. 引用Q_OBJECT宏 
    3. 使用Qt的moc编译头文件,并将编译完成之后的moc_*.cpp文件添加到工程中来。 
    当然,这过程中,你引用到的Qt头文件,lib文件,都需要你手动指定好路径和依赖库。

    https://blog.csdn.net/snail_hunan/article/details/48634427

  • 相关阅读:
    192021
    191020
    magento注册
    magento登陆
    把PHP的数组变成带单引号的字符串
    magento直接操作数据库
    兼容各大浏览器的event获取
    手动修改magento域名
    微信支付中的jsapi返回提示信息
    CentOS 下安装xdebug
  • 原文地址:https://www.cnblogs.com/findumars/p/9581615.html
Copyright © 2011-2022 走看看