仅在dereived类中从基类向现有Q_PROPERTY添加选项

时间:2017-07-05 14:58:05

标签: c++ qt5 qmetaobject

我有一个非常简单的基类,用READ和NOTIFY定义了一个普通的Q_PROPERTY(WRITE不是所有可能的实现)。

class BaseClass : public QObject {
    Q_OBJECT
    Q_PROPERTY(QStringList someEntries READ someEntries NOTIFY someEntriesChanged)

public:
    explicit BaseClass(QObject *parent = Q_NULLPTR) : QObject(parent) {}
    virtual ~BaseClass() {}

    virtual QStringList someEntries() const = 0;

    void processEntries() {
        for(auto entry : someEntries()) {
            //process entry
        }
    }

Q_SIGNALS:
    void someEntriesChanged(const QStringList &someEntries);
};

现在我有2个dereiving类,其中一个只支持一个条目(SingleItem),另一个支持多个条目(MultiItem)。

SingleItem在请求时将一个QString成员转换为QStringList,并允许使用不同的属性(theEntry)设置它:

class SingleItem : public BaseClass {
    Q_OBJECT
    Q_PROPERTY(QString theEntry READ theEntry WRITE setTheEntry NOTIFY theEntryChanged);

public:
    explicit SingleItem(QObject *parent = Q_NULLPTR) : BaseClass(parent) {}
    virtual ~SingleItem() {}

    const QString &theEntry() const { return m_theEntry; }
    void setTheEntry(const QString &theEntry) {
        if(m_theEntry != theEntry)
            Q_EMIT theEntryChanged(m_theEntry = theEntry);
    }

    // BaseClass interface
    QStringList someEntries() const Q_DECL_OVERRIDE
    { return QStringList { m_theEntry }; }

Q_SIGNALS:
    void theEntryChanged(const QString &theEntry);

private:
    QString m_theEntry;
};

MutliItem存储QStringList(用于someEntries)。我想使用BaseClass中定义的属性写入QStringList。但我不知道如何将WRITE选项添加到已定义的Q_PROPERTY。

class MultiItem : public BaseClass {
    Q_OBJECT
    //Somehow add the setSomeEntries method to the property?

public:
    explicit MultiItem(QObject *parent = Q_NULLPTR) : BaseClass(parent) {}
    virtual ~MultiItem() {}

    void setSomeEntries(const QStringList &someEntries) {
        if(m_someEntries != someEntries)
            Q_EMIT someEntriesChanged(m_someEntries = someEntries);
    }

    // BaseClass interface
    QStringList someEntries() const Q_DECL_OVERRIDE{ return m_someEntries; }

private:
    QStringList m_someEntries;
};

我无法在BaseClass中添加WRITE选项,因为它会违反其含义。并非BaseClass的每个对象都允许设置该属性,但只应使用该属性写入MultiItem的对象。

如果没有向virtual ... = 0中的BaseClass声明WRITE选项,只是在SingleItem中调用时会记录警告,这是否可行?

0 个答案:

没有答案