2015-09-12 36 views
1

直升機那裏,設置的QList子對象

我設置一個對象來獲得它在QML ......在這個對象的定義,我得到

(location_in_my_computer):25: candidate constructor 
not viable: no known conversion from 'QList<QString>' to 'QList<const QString> &' 
for 10th argument GroupObject(..., 
    ^

在我的代碼我使用這個類(最小舉例):

class GroupObject : public QObject 
{ 

public: 
    GroupObject(QObject *parent=0); 
    GroupObject( 
       QList<const QString> &tags, QObject *parent=0); 

    QList<const QString> tags(); 

    void setTags(QList<const QString> &tags); 

private: 
    QList<QString> m_tags; 
}; 

而他實現:

#include "groupobject.h" 

GroupObject::GroupObject(QList<const QString> &tags, QObject *parent) QObject(parent), 
    m_tags(tags){ 

    } 

QList<const QString> GroupObject::tags() 
{ 
    return m_tags; 
} 

void GroupObject::setTags(QList<const QString> &tags) 
{ 
    if(tags != m_tags){ 
     m_tags = tags; 
    } 
} 

我打電話約定GroupObject之一的QList在如下例子:

QList<QString> tags; 
QList<QObject*> dataList; 
dataList.append(new GroupObject(tags)); 

我怎麼能在正確的概念做到這一點?

由於

回答

3

類型的tagsQList<QString>,然而GroupObject contrustuctor接受QList<const QString>

實際上QStringconst修飾符在QList中沒有任何意義,因爲它不能保護QList修改。它只是拒絕修改QList項目。在這種情況下,在QList初始化過程中,您甚至不能複製一個這樣的QList項目。

因此,要編譯您的代碼,您必須更改QList<const QString>QList<QString>。在有些地方,你可能還需要從修改實際QList物體保護,例如:

// do not allow GroupObject(...) to change external 'tags' instance 
GroupObject(const QList<QString> &tags, QObject *parent=0); 

// return reference to internal object field and 
// do not allow callers to use that reference for changing that internal field 
// it does not change instance of GroupObject, so 
// there is 'const' modifier of the member function. 
const QList<QString>& tags() const; 

// or provide full copy of returned object 
QList<QString> tags() const; 

// do not allow to change external 'tags' inside 'setTags()' 
void setTags(const QList<QString> &tags); 

順便說一句,有QStringList類的Qt爲QString提供額外的功能列表。

2

如果您不需要通過值來傳遞它,那麼QList<QObject*> dataList是不必要的。 A QObject也是擁有對象的容器。因此,你也可以這樣寫:

class F { 
    QObject data; 
    ... 
    void foo() { 
    QStringList tags = ...; 
    new GroupObject(tags, &data); 
    ... 
    } 
    void bar() { 
    // iterate all data objects 
    for (auto obj : data.children()) { 
     auto group = qobject_cast<GroupObject>(obj); 
     if (group) { qDebug() << group.tags(); continue; } 
     ... 
    } 
    } 
} 

通過利用一個QObject作爲其他對象的容器擁有,你不必擔心資源泄漏。它將刪除它擁有的所有孩子。由於您按價值持有data,因此您甚至不需要編寫析構函數。利用編譯器爲你管理資源,它很擅長:)