我收到这个错误:
/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
类的对象? (person1
和 person2
的父级必须是 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();
}
最佳答案
在 person1(this, 100)
行中,您将 this
传递给 Person
构造函数,并将 this
在当前上下文中是 Bus
。但是构造函数期望 QAbstractItemModel
作为父级。
因为 Bus 不是 QAbstractItemModel 的子类,所以您会收到编译器错误。
要使其工作,要么使 Bus 成为 QAbstractItemModel 的衍生物,要么将 Person 构造函数更改为 explicit Person(QObject *parent = 0, int shoe_color=0);
关于c++ - 从构造函数创建 QAbstractItemModel 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41663093/