Tobias Tobias - 3 months ago 25
C++ Question

Qt/Qml: Custom widget -- cannot set "width" property as it is readonly

I have created a custom widget called

OpenGLWidget
which I have registered with the
qmlRegisterType
function.

Nested inside the Qml file, I have this:

OpenGLWidget {
id: glwidget
width: parent.width
}


My app dies saying that
width
is a readonly property.

I have also tried adding this line to the
OpenGLWidget
header file:

Q_PROPERTY(int width READ width WRITE setWidth NOTIFY widthChanged)


(However, even if these methods are not there, the code still compiles -- why?)

Anyway, it seems to me like
Q_PROPERTY
is used if you want to add your own custom properties, but properties like
x
,
y
,
width
,
height
, etc (which are all readonly) ought to be built-in, no?

EDIT:
OpenGLWidget
header file upon request.

#ifndef OPENGLWIDGET_H
#define OPENGLWIDGET_H

#include <QObject>
#include <QGLWidget>

class OpenGLWidget : public QGLWidget
{
Q_PROPERTY(int width READ width WRITE setWidth NOTIFY widthChanged)

public:
OpenGLWidget();

void setWidth(int width) { resizeGL(width, this->geometry().height()); }
void widthChanged(int width) { }

protected:
void initializeGL();
void paintGL();
void resizeGL(int width, int height);
};

#endif // OPENGLWIDGET_H

Answer

Your class is missing the Q_OBJECT macro. This causes the Qt meta object system to think of it as the closest superclass where the macro was defined, missing your method overrides.

Add Q_OBJECT line before the Q_PROPERTY line (it is needed so that the build system knows to run moc for this class). Then run qmake manually (eg. from Qt Creator build menu), because this change isn't picked up automatically so Makefiles aren't updated automatically.

It is a good idea to use Qt Creator new class wizard to add classes to a project, to avoid easy mistakes like this.