• Private implementation slots


    Private implementation slots
    Disclaimer: this article descrbes techiques that are not part of the public Qt API, using them may result in non-portable or version specific code. The example below was tested with version 4.3.3 on 64bit Linux.
    Ok so, now that we have the disclaimer out of the way... If you are a Qt developer you are probably familiar with the concept of private implementation, or "pimpl" classes. If not, well, I won't get into that here, but if you look it up on Google or Wikipedia you should get the idea fairly easily.
    Now, say you have a private class and you want it to have slots . One way is to add a slot to your public class then have it call the method you want in the private class, but this means you have to add a method to public API which means you break binary compatibility. Another is to have your private class extend QObject, but this adds overhead. Another way is to use the Q_PRIVATE_SLOT macro, which I will explain here.
    First lets look at how to set up the private class.
    file: slotTest_p.h

    #ifndef SLOTTEST_P_H_
    #define SLOTTEST_P_H_

    #include "slotTest.h"

    class slotTestPrivate
    {
    Q_DECLARE_PUBLIC(slotTest)
    public:
    slotTestPrivate(slotTest * qq) : q_ptr(qq) {}
    private:
    void bob() { qWarning("bob!"); }
    slotTest * q_ptr;
    };

    #endif

    The Q_DECLARE_PUBLIC(slotTest) macro definition is:

    #define Q_DECLARE_PUBLIC(Class) /
    inline Class* q_func() { return static_cast(q_ptr); } /
    inline const Class* q_func() const { return static_cast(q_ptr); } /
    friend class Class;

    The main purpose of this is to define a q_func()method to make sure we can accesses it with the correct const-ness and ensure its cast to the correct type. In practice, when implementing methods of the private class you should virtually never use q_func() or q_ptr directly; instead you should place the Q_Q(Class) macro, which is defined as: #define Q_Q(Class) Class * const q = q_func(), at the beginning of the method implementation. From then on in the method you can use the pointer q to refer to the public class. For example:

    void myClassPrivate::someMethod() {
    Q_Q(myClass);
    q->setText("hello world!");
    }

    Ok, so now we have our private class, lets create the public class.
    file: slotTest.h

    #ifndef SLOTTEST_H_
    #define SLOTTEST_H_

    #include <QtCore/QObject>

    class slotTestPrivate;
    class QTimer;

    class slotTest : public QObject
    {
    Q_OBJECT
    Q_DECLARE_PRIVATE(slotTest)
    public:
    slotTest();
    private:
    Q_PRIVATE_SLOT(d_func(),void bob())
    QTimer * timer;
    slotTestPrivate * d_ptr;
    };

    #endif

    It's important that you don't include the actual private file here, otherwise you will get errors like:

    slotTest_p.h:8: error: ISO C++ forbids declaration of ‘slotTest’ with no type
    slotTest_p.h:8: error: ‘slotTest’ declared as an ‘inline’ field
    slotTest_p.h:8: error: expected ‘;’ before ‘*’ token
    slotTest_p.h:8: error: expected `;' before ‘inline’
    slotTest_p.h:8: error: ISO C++ forbids declaration of ‘slotTest’ with no type
    slotTest_p.h:8: error: ‘slotTest’ declared as an ‘inline’ field
    slotTest_p.h:8: error: expected ‘;’ before ‘*’ token
    slotTest_p.h:8: error: expected `;' before ‘friend’
    make: *** [main.o] Error 1

    We have to include the Q_OBJECTmacro here even though this example class doesn't actually have any signals or slots of it's own because otherwise moc won't even look at it in the first place.
    The Q_DECLARE_PRIVATE(Class) macro is just the counterpart to the Q_DECLARE_PUBLIC(Class) macro except it creates a method named d_func() to access the private class. Likewise, there is a Q_D macro for use inside method implementations so you can use d as a pointer to the private class.
    The Q_PRIVATE_SLOT macro takes a pointer to your private class, and we will take advantage of the d_func()method to get it. Next is the signature of the private class' method to call. One interesting thing about this macro is that it directly expands to no actual code - it simply a trigger for moc.
    We are also creating a QTimer to call this slot repetadly for the example.
    Now our implementation:
    file: slotTest.cpp

    #include <QtCore/QObject>
    #include <QTimer>
    #include "slotTest.h"
    #include "slotTest_p.h"
    #include "moc_slotTest.cpp"

    slotTest::slotTest() : QObject()
    {
    d_ptr = new slotTestPrivate(this);
    timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer,SIGNAL(timeout()),this,SLOT(bob()));
    timer->start();
    }

    The most important thing to notice here is that we have listed the moc-generated moc_slotTest.cpp file as an include, doing this ensures that slotTestPrivate has been defined before the moc file is processed. If you were to not include of this file here, you may get an error like:

    /home/kdab/workspace/prtst/slotTest.h:10: undefined reference to `vtable for slotTest'

    Here, we just set up our private class, a timer, and connect the timer to call our slot. Notice that even though the method we are calling is inside our private class, we still use this in the connection because the slot is technically a slot of our public class, even though the implementation is in the private class.
    Now lets make it runnable:
    filename: main.cpp

    #include <QtCore/QCoreApplication>
    #include "slotTest.h"

    int main(int argc,char* argv[])
    {
    QCoreApplication app(argc,argv);
    slotTest bob;
    app.exec();
    }

    And one final very important thing, the project file...

    TEMPLATE = app
    TARGET =
    DEPENDPATH += .
    INCLUDEPATH += .

    # Input
    HEADERS += slotTest.h slotTest_p.h
    SOURCES += main.cpp slotTest.cpp

    It's very important that slotTest.h is listed before slotTest_p.h otherwise you will end up with the following error:

    moc_slotTest.cpp: In member function ‘virtual int slotTest::qt_metacall(QMetaObject::Call, int, void**)’:
    moc_slotTest.cpp:64: error: invalid use of undefined type ‘struct slotTestPrivate’
    slotTest.h:5: error: forward declaration of ‘struct slotTestPrivate’

    Once you have it built, you should see "bob!" printed to the screen every second from the bob() method in the private class.
  • 相关阅读:
    浅谈Dockercompose中的depends_on顺序的问题解决
    systemctl启动prometheus+grafana环境
    chrony时间同步服务简介及配置
    k8s中环境变量
    odoo开发笔记向导弹窗的selection选项,根据条件动态显示 hello
    读书笔记 《纳瓦尔宝典:财富和幸福指南》 hello
    “应用程序发布商: 未知”问题处理 hello
    HTTP重定向出现“正在中止线程”问题
    MySQL报Data too long for column '......' at row 1解决方法
    迭代器yield的使用
  • 原文地址:https://www.cnblogs.com/cute/p/2236431.html
Copyright © 2020-2023  润新知