简体   繁体   English

Qt / Qml:自定义窗口小部件-无法设置“宽度”属性,因为它是只读的

[英]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. 我创建了一个名为OpenGLWidget的自定义小部件,该小部件qmlRegisterType函数注册。

Nested inside the Qml file, I have this: 嵌套在Qml文件中,我有这个:

OpenGLWidget {
  id: glwidget
  width: parent.width
}

My app dies saying that width is a readonly property. 我的应用死于说width是只读属性。

I have also tried adding this line to the OpenGLWidget header file: 我也尝试将这一行添加到OpenGLWidget头文件中:

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? 无论如何,在我看来,如果要添加自己的自定义属性,则使用Q_PROPERTY ,但是应该将诸如xywidthheight等属性(都是只读的)内置,不是吗?

EDIT: OpenGLWidget header file upon request. 编辑: OpenGLWidget头文件应要求提供。

#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

Your class is missing the Q_OBJECT macro. 您的班级缺少Q_OBJECT宏。 This causes the Qt meta object system to think of it as the closest superclass where the macro was defined, missing your method overrides. 这导致Qt元对象系统将其视为定义宏的最接近的超类,而缺少您的方法重写。

Add Q_OBJECT line before the Q_PROPERTY line (it is needed so that the build system knows to run moc for this class). Q_PROPERTY行之前添加Q_OBJECT行(这是必需的,以便构建系统知道为此类运行moc )。 Then run qmake manually (eg. from Qt Creator build menu), because this change isn't picked up automatically so Makefiles aren't updated automatically. 然后手动运行qmake (例如,从Qt Creator构建菜单中),因为此更改不会自动获取,因此Makefile不会自动更新。

It is a good idea to use Qt Creator new class wizard to add classes to a project, to avoid easy mistakes like this. 最好使用Qt Creator的新类向导将类添加到项目中,以避免类似这样的简单错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM