0

I have an interesting issue. I don't know how to combine two classes inhereted from QObject. Base accent to my problem using Q_INVOKABLE method in derived class from base class. I want use "loadFromJson" multiple times in various "models".

I've allready trying to define Q_OBJECT macro, and rebuild the logic of classes.

//model.h
class Model : public QObject{
   Q_OBJECT
public:
   Q_INVOKABLE bool loadFromJson(const QString &data);
}

//sqltablemodel.h
class SqlTableModel : public QSqlTableModel{
   //some code
}

//server.h
class Server : public SqlTableModel, Model
{
    Q_OBJECT
public:
    explicit Server(QString tableName = "");
};

//main.cpp
Server *server =  new Server();
    context->setContextProperty("server", server);
//

//server.qml
server.loadFromJson("123"); // not working


/*
If i remove QObject from Model then i can't call loadFromJson even Q_OBJECT defined, otherwise Server is ambigous using QObject. But i want to use methods from both base classes SqlTableModel & Model in derived Server with Q_INVOKABLE ability.
*/

main.cpp:41: ошибка: ‘QObject’ is an ambiguous base of ‘Server’ context->setContextProperty("server", server);

model.h:27: ошибка: undefined reference to `vtable for Model'

2 Answers2

0

I would use a "has a" relationship instead of "is a" one. It would look something like this:

class Server : public SqlTableModel {
  Q_OBJECT
  Q_PROPERTY(Model* model READ model WRITE setModel NOTIFY modelChanged)

  Model* _model;

 public:
  explicit Server(QObject* parent = nullptr)
      : SqlTableModel(parent), _model(new Model(this)) {}

 signals:
  void modelChanged(Model* model);

 public:
  Model* model() const noexcept { return _model; }
  void setModel(Model* m) noexcept { _model = m; }
};

Then you'd call it in your qml like this: server.model.loadFromJson("123");

But also you can make Model inherit private QObject if you try harder to solve issues that arise after that.

The Moisrex
  • 1,857
  • 1
  • 14
  • 16
0

I solved the problem with changing the order of inheritence. SqlTableModel->Model->Server.