从构造函数创建QAbstractItemModel对象

时间:2017-01-15 15:56:43

标签: c++ qt

我收到此错误:

/home/niko/QT_snippets/oop2/bus.cpp:3: error: no matching function for call to ‘Person::Person(Bus*, int)’
 Bus::Bus(QObject *parent) : QObject(parent) , person1(this,100), person2(this,200)
                                                                                  ^
/home/niko/QT_snippets/oop2/bus.h:5: In file included from ../oop2/bus.h:5:0,
/home/niko/QT_snippets/oop2/bus.cpp:1: from ../oop2/bus.cpp:1:
/home/niko/QT_snippets/oop2/person.h:11: candidate: Person::Person(QAbstractItemModel*, int)
     explicit Person(QAbstractItemModel *parent = 0, int shoe_color=0);
              ^
/home/niko/QT_snippets/oop2/person.h:11: note:   no known conversion for argument 1 from ‘Bus*’ to ‘QAbstractItemModel*’

我的问题是,如何初始化成员为QAbstractModelItem类的对象? (person1person2的父级必须为Bus,因为当我删除它时,我希望将子项删除。)我尝试强制转换为(QObject*)但我得到了另一个编译错误。

这是示例的完整源代码:

//File: bus.h
#ifndef BUS_H
#define BUS_H

#include <QObject>
#include "person.h"

class Bus : public QObject
{
    Q_OBJECT
public:
    explicit Bus(QObject *parent = 0);

private:
    Person      person1;
    Person      person2;
};

#endif // BUS_H


//File: bus.cpp
#include "bus.h"

Bus::Bus(QObject *parent) : QObject(parent) , person1(this,100), person2(this,200)
{

}



//File: person.h
#ifndef PERSON_H
#define PERSON_H

#include <QObject>
#include <QAbstractItemModel>

class Person : public QAbstractItemModel
{
    Q_OBJECT
public:
    explicit Person(QAbstractItemModel *parent = 0, int shoe_color=0);
    QModelIndex index(int row, int column,const QModelIndex &parent = QModelIndex()) const;
    QModelIndex parent(const QModelIndex &child) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
private:
    int m_shoe_color;
};

#endif // PERSON_H


//File: person.cpp
#include "person.h"

Person::Person(QAbstractItemModel *parent,int shoe_color) : QAbstractItemModel(parent)
{
    m_shoe_color=shoe_color;
}
QModelIndex index(int row, int column,const QModelIndex &parent = QModelIndex()) const {

}
QModelIndex parent(const QModelIndex &child) const {

}
int rowCount(const QModelIndex &parent = QModelIndex()) const {

}
int columnCount(const QModelIndex &parent = QModelIndex()) const {

}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {

}



//File: main.cpp
#include <QCoreApplication>
#include "person.h"
#include "bus.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Bus b;
    return a.exec();
}

1 个答案:

答案 0 :(得分:1)

person1(this, 100)行中,您将this传递给Person构造函数,当前上下文中的thisBus。但构造函数期望QAbstractItemModel为父级。

因为Bus不是QAbstractItemModel的子类,所以会出现编译错误。

要使其工作要么使Bus成为QAbstractItemModel的衍生物,要么将Person构造函数更改为explicit Person(QObject *parent = 0, int shoe_color=0);