QML can see my Q_GADGET but not Q_OBJECT - c++

Why can my Q_GADGET be read perfectly in QML (JS) but not my Q_OBJECT?
Running Qt 5.8.0 on Ubuntu 14.04.
I'm attempting to return a list (QVariantMap) of objects to QML. I'm keeping it simple right now, no pointers, etc.. just copies of the objects.
struct Blob
{
Q_GADGET
Q_PROPERTY(QString uuid MEMBER uuid_ CONSTANT)
Q_PROPERTY(QVector3D centroid MEMBER centroid_)
// ...
Blob() {};
~Blob() = default;
Blob(const Blob& blob);
};
Q_DECLARE_METATYPE(Blob)
There are a bunch of QString and QVector3D members on Blob.
In main.cpp, I also register the type:
qmlRegisterType<Blob>("matt", 1, 0, "Blob");
Then my JS code is able to read all the properties (for loop iterating over them) on the object without issue.
But if I use a Q_OBJECT
struct Blob : public QObject
{
Q_OBJECT
Q_PROPERTY(QString uuid MEMBER uuid_ CONSTANT)
Q_PROPERTY(QVector3D centroid MEMBER centroid_)
// ...
explicit Blob(QObject parent = nullptr) : QObjecT(parent) {};
~Blob() = default;
Blob(const Blob& blob);
};
Q_DECLARE_METATYPE(Blob)
Then the JS receives an object where all the properies are the keys from the QVariantMap, but whose values are empty objects.
Note, before sending it to the JS, I convert it to a QVariant and back again just to confirm that that works, e.g.
Blob b;
qDebug() << "Created: " << b;
QVariant var = QVariant::fromValue(b);
qDebug() << " Converted back = " << var.value<Blob>().toQString();
I'd prefer to use a Q_OBJECT such that I have slots/signals.

The reason I was seeing a difference between Q_OBJECT and Q_GADGET was that I was making copies of my object, which is allowed on a Q_GADGET (a value) object, but not on a Q_OBJECT (an identity object.) See identities instead of values.
The solution is to always work on Q_OBJECTs with pointers. This maintains their identity, and avoid copies.
Also, my original intent was to use a smart pointer, but the reasons why that is a bad approach are explained in this answer.
The comment by #dtech also explained that Q_DECLARE_METATYPE is redundant on a Q_OBJECT.
Thus, my final declaration is:
i.e.
class Blob : public QObject
{
Q_OBJECT
Q_PROPERTY(QString uuid MEMBER uuid_ CONSTANT)
Q_PROPERTY(QVector3D centroid MEMBER centroid_)
// ...
explicit Blob(QObject parent = nullptr) : QObjecT(parent) {};
~Blob() = default;
Blob(const Blob& blob);
};
With this, I can easily put a raw pointer to these objects in a QVariantMap, and they can be read on the QML/JS side.

Related

C++ member variable class Q_PROPERTY not available in QML

I am attempting to make a new QML QQuick object that will contain a sub-object of QQuickPaintedItem.
Below is a shortened portion of my c++ code
// PDFDocument.h //
class PDFDocument : public QQuickItem
{
public:
Q_OBJECT
Q_PROPERTY( PDFPageView* pageView READ getPageView )
PDFDocument( QQuickItem* parent = nullptr );
~PDFDocument();
PDFPageView* getPageView() { return &m_pageView; }
private:
PDFPageView m_pageView;
};
//PDFDocument.cpp//
PDFDocument::PDFDocument( QQuickItem* parent /*= nullptr*/ )
:QQuickItem( parent )
{
}
//PDFPageView.h//
class PDFPageView : public QQuickPaintedItem
{
public:
Q_OBJECT
Q_PROPERTY( int dpi MEMBER m_dpi NOTIFY dpiChanged )
Q_SIGNALS:
void dpiChanged();
public:
PDFPageView( QQuickItem* parent = nullptr );
~PDFPageView();
void paint( QPainter* painter_p );
private:
int m_dpi = 144; //default dpi to 144
};
Next is the actual QML snippet
PDFDocument
{
id: pdfDocument
anchors
{
fill: parent
centerIn: parent
}
pageView.dpi: 200 //Invalid grouped property access
}
The type is registered in the engine as well
qmlRegisterType<PDFDocument>( "Nordco.TechPubs", 1, 0, "PDFDocument" );
qmlRegisterType<PDFPageView>( "Nordco.TechPubs", 1, 0, "PDFPageView" );
For some reason I am getting an Invalid grouped property access error in the QML. I marked it with a comment in the qml code snippet.
I shortened the code because I have quite a bit, but can edit this post if i forgot to show anything. I feel like I am missing something simple here but cannot seem to get a helpful error. Any ideas?
It appears that I needed to include my namespaces when declaring a Q_Property because it is a macro. Now the custom member variable is accessable.
Q_PROPERTY( TechnicalPublications::PDFPageView* pageView READ getPageView )
Of course in shortening the problem, I excluded the namespaces my classes exist in.

How to use QScxmlCppDataModel in QScxmlStateMachine?

In my project , i use C++ , QScxmlCppDataModel , there is always occur a error , "No data-model instantiated" when i start the state machine,
I follow the Qt document says
1、Add data model in scxml file
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" binding="early" xmlns:qt="http://www.qt.io/2015/02/scxml-ext" datamodel="cplusplus:DataModel:DataModel.h" name="PowerStateMachine" qt:editorversion="4.6.1" initial="nomal">
2、Create a new data model subclass
#include "qscxmlcppdatamodel.h"
#include <QScxmlEvent>
class DataModel :public QScxmlCppDataModel
{
Q_OBJECT
Q_SCXML_DATAMODEL
public:
// DataModel();
bool isMoreThan50() const;
bool isLessThan50() const ;
int m_power;
QString m_Descript;
QVariant m_var;
};
3、load and start state machine
m_stateMachine = QScxmlStateMachine::fromFile(":/powerStateMachine.scxml");
for(QScxmlError& error:m_stateMachine->parseErrors())
{
qDebug()<<error.description();
}
m_stateMachine->connectToEvent("powerLoss", this, &MainWindow::onPowerLossEvent);
m_stateMachine->connectToEvent("pwoerUp", this, &MainWindow::onPowerUpEvent);
m_stateMachine->connectToState("low", this, &MainWindow::onLowState);
m_stateMachine->connectToState("nomal", this, &MainWindow::onNomalState);
m_stateMachine->connectToState("danger", this, &MainWindow::onDangerState);
m_stateMachine->connectToState("full", this, &MainWindow::onFullState);
DataModel *dataModel = new DataModel;
m_stateMachine->setDataModel(dataModel);
m_stateMachine->init();
m_stateMachine->start();
error image
but still have a error :"No data-model instantiated",when i start the
state machine , anybody know how to fix it ?? thank you
Qt's documentation on QScxmlCppDataModel specifically says:
The C++ data model for SCXML ... cannot be used when loading an SCXML
file at runtime.
And that is exactly what you are doing, so instead of loading the scxml file at runtime:
m_stateMachine = QScxmlStateMachine::fromFile(":/powerStateMachine.scxml");
Use the compiled statemachine directly:
MyStateMachine statemachine;
MyDataModel datamodel;
statemachine.setDataModel(&datamodel);
In the example above:
1- MyStateMachine is the value you have assigned to the <name> attribute of the scxml element (i.e. scxml file/model).
2- MyDataModel is the name you have given to your c++ data model class (i.e. your class derived from QScxmlCppDataModel)
class MyDataModel : public QScxmlCppDataModel
{
Q_OBJECT
Q_SCXML_DATAMODEL
public:
MyDataModel();
};
Too late an answer, but hope it helps others.

Send object from c++ to qml. What about free memory?

There is a model inherited from QAbstractListModel, I use it in qml. One of the properties of this model are parameters, they are specific to the element type of this model. That is one element the parameters of this class TemperatureParam, DifrentParamType another, a third still something... How can I pass an object to qml and to be sure that the memory is freed after use? The code below now works as I need to, but it seems to me that it's not safe.
Param class is so trivial:
class QuickTemperatureParam : public QObject
{
Q_OBJECT
Q_PROPERTY(float param1 READ param1 WRITE setParam1)
//...
};
Model class (Here's what I'm asking):
class SectionsModel : public QAbstractListModel
{
//...
QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override
{
//...
int type = getType( idx );
if (type == 1)
{
auto p = new QuickTemperatureParam( idx );
p->deleteLater(); // This is all right or no?
return qVariantFromValue(p);
}
else if (type == 2)
//...
}
};
QML something like this:
ListView {
model: sectionsModel
delegate: Rectangle {
color: model.statusColor
ItemDelegate {
text: model.title
highlighted: ListView.isCurrentItem
onPressed:
switch ( model.type )
{
case SectionType.Temperature:
temperatureParam.openItem(model)
break;
case SectionType.Lighting:
lightingParam.open(model)
break;
}
}
}
}
Popup {
id: temperatureParam
function openItem(model)
{
var p = model.param
params.itemAt(0).range.from = params.itemAt(1).range.from = p.min
params.itemAt(0).range.to = params.itemAt(1).range.to = p.max
params.itemAt(0).range.setValues( p.dayMin, p.dayMax )
params.itemAt(1).range.setValues( p.nightMin, p.nightMax )
open()
}
}
According to the documentation:
When data is transferred from C++ to QML, the ownership of the data
always remains with C++. The exception to this rule is when a QObject
is returned from an explicit C++ method call: in this case, the QML
engine assumes ownership of the object, unless the ownership of the
object has explicitly been set to remain with C++ by invoking
QQmlEngine::setObjectOwnership() with QQmlEngine::CppOwnership
specified.
Generally an application doesn't need to set an object's ownership explicitly. As you can read here, by default, an object that is created by QML has JavaScriptOwnership.
Objects returned from C++ method calls will be set to JavaScriptOwnership also but this applies only to explicit invocations of Q_INVOKABLE methods or slots.
Because the method data is not an explicit C++ method call, you should consider to set the object ownership to QQmlEngine::JavaScriptOwnership calling setObjectOwnership()
So, in general:
Don't use QQmlEngine::CppOwnership if you want QML to destroy the object. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value)
A QSharedPointer probably wouldn't work. You have more information here.

Why is QObject ::findChildren returning children with a common base class?

I am using QObject as a base class for a composite pattern.
Say I have a parent class File (in a contrived example) to which I am adding children of different types, HeaderSection and PageSection. File, HeaderSection and PageSection are all Sections. The constructor for Section takes a parent object which is passed through to QObject's constructor, setting the parent.
e.g:
class Section : public QObject {
Q_OBJECT
// parent:child relationship gets set by QObject
Section(QString name, Section *parent=NULL) : QObject(parent)
{ setObjectName(name);}
QString name(){return objectName();}
};
class File: public Section {
public:
// probably irrelevant to this example, but I am also populating these lists
QList<Section *> headers;
QList<Section *> pages;
};
class Header : public Section {
Header(QString name, File *file) : Section(name, file){}
};
class Page: public Section {
Body(QString name, File *file) : Section(name, file){}
};
Syntax for construction in the definition may be incorrect, apologies, I'm used to doing it outside. Anyway, when I do this:
File *file = new file();
Header *headerA = new Header("Title", file);
Header *headerB = new Header("Subtitle", file);
Page *page1 = new Page("PageOne", file);
Page *page2 = new Page("PageTwo", file);
QList<Page*> pages = file->findChildren<Page*>();
for(int i=0; i < pages.size(); i++)
qDebug() << pages.at(i)->name();
I get the following output:
Title
Subtitle
PageOne
PageTwo
What am I missing here? Surely if findChildren looked for common base classes then it would only ever return every single child of a Widget (for example), which I know it doesn't in normal use.
Also, if I iterate over the list of children returned and use dynamic_cast<Page*> on each returned child, I get the expected two Page items.
The answer is as #Mat and #ratchet freak tell me - I needed Q_OBJECT in every subclass, not just the base class.

How to create a generic object model for use in QML?

I would like to know if there is any macro or way how to register Qt model as property of QObject.
For example, I have AnimalModel (http://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html#qabstractitemmodel).
I Know I can pass it to root context of QuickView
QuickView view;
view.rootContext()->setContextProperty("myModel", &model);
In case I have QObject registered via Qml macros, I can pass this object to view too:
view.rootContext()->setContextProperty("obj", pDataObject);
But what If I want to have QObject which holds model of any data?
For example:
class DataObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged)
...
AnimalModel m_modelAnimals;
//Is this possible in any way?
//Q_PROPERTY(AnimalModel modelAnimals READ modelAnimals NOTIFY modelAnimalsChanged)
};
Every example I found until now shows how to pass QAbstractListModel to root context. But none how to use it as QObject property.
(I know there is QQmlListProperty but QQmlListProperty doesn't support partial refresh. It's always necessary to rebuild all Qml objects)
//Is this possible in any way?
//Q_PROPERTY(AnimalModel modelAnimals READ modelAnimals NOTIFY modelAnimalsChanged)
Yes it is, didn't you try? Of course, it will not be a AnimalModel but a AnimalModel *, but as long as the model inherits QAbstractListModel, that's all you need. You don't even need the NOTIFY part, as changes, internal to the model will be automatically reflected anyway. modelAnimalsChanged only makes sense when you replace the entire model with a different model, and naturally, to shut up QML's warnings about using a property without a notify signal. A cleaner way to do the latter when the model object doesn't change is to just return a AnimalModel * from a slot or a Q_INVOKABLE.
If you want a truly flexible model, you can make one that stores QObject *, then from QML you can create arbitrary objects with arbitrary properties, and add to the model. Then from the model you have a single object role which returns the object, and you can query and use the object to retrieve the properties it holds. Whereas a "classical" list model implementation will define a model with a static, fixed schema, using this approach allows to have "amorphous" objects in the model with different properties.
Naturally, this requires some type safety, for example have a property int type for each object in such a model, and based on it you can determine the available properties for the object. My usual approach is to have a Loader for a delegate, and have it pass the object as a data source to different QML UI implementations visualizing that object type that it instantiates. This way you have both different objects in the model, and different QML items as view delegates.
The last step to making the ultimate "jack of all trades" list/model object is to implement QQmlListProperty and Q_CLASSINFO("DefaultProperty", "container") for it, allowing you to both compose the list/model dynamically, or using QML's declarative syntax. Also note that with this solution, you can add to or remove from such a model, even remove declaratively instantiated objects.
Also, depending on your usage scenario, you may have to either qmlRegisterType() or qmlRegisterUncreatableType() for the model.
OK, on a second glance, it looks like by "model of any data" you didn't mean schema-less models but simply different schema models. In that case, instead of returning an AnimalModel *, you can use a QAbstractListModel * or even a QObject * - it will work in QML anyway, as it employs dynamism through the meta system. But at any rate, schema-less models are that much more powerful and flexible, and they don't need C++ code to be defined, it can all work from QML alone.
class List : public QAbstractListModel {
Q_OBJECT
QList<QObject *> _data;
Q_PROPERTY(int size READ size NOTIFY sizeChanged)
Q_PROPERTY(QQmlListProperty<QObject> content READ content)
Q_PROPERTY(QObject * parent READ parent WRITE setParent)
Q_CLASSINFO("DefaultProperty", "content")
public:
List(QObject *parent = 0) : QAbstractListModel(parent) { }
int rowCount(const QModelIndex &p) const { Q_UNUSED(p) return _data.size(); }
QVariant data(const QModelIndex &index, int role) const {
Q_UNUSED(role)
return QVariant::fromValue(_data[index.row()]);
}
QHash<int, QByteArray> roleNames() const {
static QHash<int, QByteArray> roles = { { Qt::UserRole + 1, "object" } };
return roles;
}
int size() const { return _data.size(); }
QQmlListProperty<QObject> content() { return QQmlListProperty<QObject>(this, _data); }
public slots:
void add(QObject * o) { insert(o, _data.size()); }
void insert(QObject * o, int i) {
if (i < 0 || i > _data.size()) i = _data.size();
beginInsertRows(QModelIndex(), i, i);
_data.insert(i, o);
o->setParent(this);
sizeChanged();
endInsertRows();
}
QObject * take(int i) {
if ((i > -1) && (i < _data.size())) {
beginRemoveRows(QModelIndex(), i, i);
QObject * o = _data.takeAt(i);
o->setParent(0);
sizeChanged();
endRemoveRows();
return o;
} else qDebug() << "ERROR: take() failed - object out of bounds!";
return 0;
}
QObject * get(int i) {
if ((i > -1) && (i < _data.size())) return _data[i];
else qDebug() << "ERROR: get() failed - object out of bounds!";
return 0;
}
void internalChange(QObject * o) { // added to force sort/filter reevaluation
int i = _data.indexOf(o);
if (i == -1) {
qDebug() << "internal change failed, obj not found";
return;
} else {
dataChanged(index(i), index(i));
}
}
signals:
void sizeChanged();
};
Then, after you qmlRegisterType<List>("Core", 1, 0, "List"); you can use it pretty much any way you want to - it will hold any QObject or derived, naturally including QMLs QtObject It can directly be used as a model to drive a ListView. You can populate it dynamically using the slots or declarative, like this:
List {
QtObject { ... }
QtObject { ... }
List {
QtObject { ... }
QtObject { ... }
}
}
It will also handle object ownership, and you can easily nest it, producing in essence a compartmentalized tree model - note that you can't declaratively do that with QML's ListModel. You may want to add a parentChanged signal and implement a setter that emits it if you want to bind against a changing parent, it was not necessary in my case.
As of how to use it with a view, you can either use the objectName property or an int type property or basically any means to discern between different object types, and use a Loader for the delegate:
Loader {
// using component in order to capture context props and present to the variable delegate
sourceComponent: Qt.createComponent(obj.objectName + ".qml")
// if that is not needed simply use
// source: obj.objectName + ".qml"
// or setSource to pass specific properties to delegate properties
// Component.onCompleted: setSource(obj.objectName + ".qml", {/*prop list*/})
}
Update:
Here is also the gist of the implementation for a simple and just as dynamic and generic sorting and filtering proxy to go with this model for enhanced usability.