[Interest] Why is this not working? Assign direct to QML (through setContextProperty) works, as function doesn't.

Robert Voinea rvoinea at gmail.com
Mon Nov 12 15:12:49 CET 2012



[snip]
> >> That would be very nice :)
> > First of all... the bug I was talking about is this
> > https://bugreports.qt-project.org/browse/QTBUG-13047
> > But it seems to be fixed in Qt 4.7.1
> > 
> > Well... I'd use something like this:
> > pathmodel.h
> > 
> > class PathModel : public QStringListModel
> > {
> > public:
> > explicit PathModel(QObject *parent = 0);
> > };

> > util.h
> > 
> > class Util : public QObject
> > {
> > Q_OBJECT
> > Q_PROPERTY(QObject* pathModel READ pathModel CONSTANT)
> > public:
> > ...
> > PathModel* pathModel() { return &m_pathModel; };
> > Q_INVOKABLE QString testString() { return "some_test_text"; }
> > 
> > private:
> > PathModel m_pathModel;
> > };
> > with the downside of having to include the header for pathModel.
> > As far as I know every variable, item, etc in QML is a QVariant.
> > 
> > For QObject-derived classes their properties are exposed to QML and used
> > through the QObject interface.
> > --
> 
> Oke, i wasn't expecting that. I added the Q_PROPERTY(QObject*
> pathModel READ pathModel CONSTANT) stuff to my code (and removed the
> Q_INVOKABLE from my pathModel method), changed the code to use the new
> property and amazingly it worked!

> Why isn't this clearly documented _anywhere_? I certainly can use
> google and know the Qt docs quite well, but i haven't found anything
> that would indicate me to do it this way.

Look here:
http://doc.qt.digia.com/qt/qml-extending.html

> Another question, how can i get the same stuff working as a function
> call? Now it works as a Q_PROPERTY which is fine for my case, but i'm
> just curious about the same for a function call.

Well... for function call just use the following:

class Util : public QObject
{
	Q_OBJECT
public:
	...
	// PathModel* pathModel() { return &m_pathModel; };
	// As I said, you use the QObject interface for your PathModel	
	Q_INVOKABLE QObject* pathModel() { return &m_pathModel; };
	Q_INVOKABLE QString testString() { return "some_test_text"; }
private:
	PathModel m_pathModel;
};

All these macros are described in the documentation for QObject
	http://doc.qt.digia.com/qt/qobject.html#Q_INVOKABLE
See also:
	http://doc.qt.digia.com/qt/metaobjects.html#meta-object-system

-- 
Robert Voinea
Software Engineer
+4 0740 467 262

Don't take life too seriously. You'll never get out of it alive.
(Elbert Hubbard)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20121112/18cebd93/attachment.html>


More information about the Interest mailing list