我正在尝试使用C ++类扩展QML。我首先创建了一个简单的类Line
。它调用setter,但不调用getter和paint
方法。有什么想法吗?在QtQuick 1.x中,我应该在构造函数中调用setFlag(QGraphicsItem::ItemHasNoContents, false);
。可能我应该说类似的东西?
以下是代码:
Line.h
#ifndef LINE_H
#define LINE_H
#include <QQuickPaintedItem>
class Line : public QQuickPaintedItem
{
Q_OBJECT
Q_PROPERTY(int x1 READ x1 WRITE setx1 NOTIFY x1Changed)
Q_PROPERTY(int y1 READ y1 WRITE sety1 NOTIFY y1Changed)
Q_PROPERTY(int x2 READ x2 WRITE setx2 NOTIFY x2Changed)
Q_PROPERTY(int y2 READ y2 WRITE sety2 NOTIFY y2Changed)
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
Q_PROPERTY(int penWidth READ penWidth WRITE setPenWidth NOTIFY penWidthChanged)
public:
Line(QQuickItem *parent = nullptr);
~Line();
void paint(QPainter *painter) override;
int x1() const;
...
signals:
void x1Changed(int arg);
...
public slots:
void setx1(int arg);
...
private:
int m_x1;
...
};
#endif // LINE_H
Line.cpp
#include "Line.h"
#include <QPen>
#include <QPainter>
Line::Line(QQuickItem *parent) : QQuickPaintedItem(parent)
{
}
Line::~Line()
{
}
void Line::paint(QPainter *painter)
{
QPen pen(m_color, m_penWidth);
painter->setPen(pen);
int x = qMin(m_x1, m_x2) - m_penWidth/2;
int y = qMin(m_y1, m_y2) - m_penWidth/2;
painter->drawLine(m_x1 - x, m_y1 - y, m_x2 - x, m_y2 - y);
}
int Line::x1() const
{
return m_x1;
}
...
void Line::setx1(int arg)
{
if (m_x1 == arg)
return;
m_x1 = arg;
emit x1Changed(arg);
}
...
同样很明显,我已在main
添加了我的课程注册:
qmlRegisterType(“extentiongui”,1,0,“Line”);
我的QML代码:
Line {
id: lineDelimiter
x1: 863
x2: 863
y1: 660
y2: 800
penWidth: 8000
color: "#c2c2c2"
}
答案 0 :(得分:1)
如果您的项目包含可视内容,则应设置QQuickItem::ItemHasContents
标记。
setFlag(QQuickItem::ItemHasContents, true);
此外,您应该在setter函数中调用update()
来重绘项目。
void Line::setx1(int arg)
{
if (m_x1 == arg)
return;
m_x1 = arg;
emit x1Changed(arg);
update();
}