Subclass of QObject, qRegisterMetaType, and the private copy constructor

前端 未结 5 1981
有刺的猬
有刺的猬 2020-12-10 04:21

I have a class that is a subclass of QObject that I would like to register as a meta-type. The QObject documentation states that the copy-constructor should be private, but

5条回答
  •  失恋的感觉
    2020-12-10 05:14

    What you're asking for is perfectly ok. You can't use QObjects copy constructor (it's private) in the implementation of your copy constructor, but then again, no-one forces you to:

    class MyClass : public QObject {
        Q_OBJECT
    public:
        // ...
        MyClass( const MyClass & other )
            : QObject(), i( other.i ) {} // NOTE: calling QObject default ctor
        // ...
    private:
        int i;
    };
    

    Depending on what services you need from QObject, you need to copy some properties over from other, in both the copy ctor and the copy assignment operator. E.g., if you use QObject for it's dynamic properties feature, you'd need to copy those, too:

        MyClass( const MyClass & other )
            : QObject(), i( other.i )
        {
            Q_FOREACH( const QByteArray & prop, other.dynamicPropertyNames() )
                setProperty( prop.constData(), other.property( prop.constData() ) );
        }
    

    Likewise, if you want to maintain signal/slot connections.

提交回复
热议问题