Where to make initialization of members of QML type?
I generated a custom type polygon
Polygon {
id: aPieChart
anchors.centerIn: parent
width: 100; height: 100
name: "A simple polygon"
color: "blue"
vertices:[
开发者_StackOverflow Point{x:20.0; y:40.0},
Point{x:40.0; y:40.0},
Point{x:20.0; y:20.0}
]
}
Here is my polygon.h file:
#ifndef POLYGON_H
#define POLYGON_H
#include <QDeclarativeItem>
#include <QColor>
#include "point.h"
class Polygon : public QDeclarativeItem
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(QColor color READ color WRITE setColor)
Q_PROPERTY(QDeclarativeListProperty<Point> vertices READ vertices)
public:
Polygon(QDeclarativeItem *parent = 0);
QString name() const;
void setName(const QString &name);
QColor color() const;
void setColor(const QColor &color);
QDeclarativeListProperty<Point> vertices();
static void append_vertex(QDeclarativeListProperty<Point> *list, Point *vertex);
//void Polygon::dragEnterEvent(QGraphicsSceneDragDropEvent *event);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
private:
QString m_name;
QColor m_color;
QList<Point *> m_vertices;
};
#endif // POLYGON_H
Point is also a type generated by me.
I handle vertices with a line in polygon.h:
Q_PROPERTY(QDeclarativeListProperty<Point> vertices READ vertices)
because of the need to use points as a QVector,
i use these lines, m_vertices is the variable name that handle vertices array got from QML:
QVector<QPointF> vPnt;
for(int i=0;i<m_vertices.length();i++){
vPnt.append(QPointF(m_vertices.at(i)->x(),m_vertices.at(i)->y()));
}
I want to ask where should i put these lines. In paint? Then these lines run again and again where paint is called? In constructer then, m_vertices is not initialized that time? Thanks for any idea.
According to the documentation if your Polygon inherits from QDeclarativeItem then you can also implement the QDeclarativeParserStatus interface and you will be notified when the component is ready and values have been initialized.
That looks like a good place where to update your vPnt QVector.
(I haven't tested this solution personally)
精彩评论