所以我看了here提供的涂鸦示例,我想我想在QML中实现类似的东西。考虑一下之后,我认为使用自定义QQuickPaintedItem
将是最好的工具。所以我想出了一个超级简约的例子:
#include "drawingcanvas.h"
#include <QPainter>
DrawingCanvas::DrawingCanvas(QQuickItem *parent) : QQuickPaintedItem(parent)
{
lastPoint = QPointF(0,0);
}
void DrawingCanvas::mouseMoved(const QPointF &pos)
{
points.append(pos); // points is a QVector<QPointF>
currentPoint = pos;
this->update(QRect(lastPoint.toPoint(), currentPoint.toPoint()));
}
void DrawingCanvas::paint(QPainter *painter)
{
painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter->setPen(QPen(QColor("blue"), 5, Qt::SolidLine, Qt::RoundCap,
Qt::RoundJoin));
for(int j = 1; j < points.length(); ++j){
painter->drawLine( points.at(j - 1), points.at(j));
}
lastPoint = currentPoint;
}
在QML中,我写了一个简单的MouseArea
和自定义类,如下所示:
import QtQuick 2.12
import QtQuick.Window 2.12
import Drawing 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
DrawingCanvas {
id: drawingCanvas
anchors.fill: parent
}
MouseArea {
anchors.fill: parent
onPositionChanged: drawingCanvas.mouseMoved(Qt.point(mouseX, mouseY))
}
}
代码无法按预期工作(上图显示如果我绘制“快速”直线会出现一些渲染问题),原因是QQuickPaintedItem::update
函数仅计划调用{{1} },但不会立即调用它。我认为还有其他问题(我对QQuickPainteItem和QPainter不太熟悉)。无论如何,我决定停下来,因为我认为这可能不是实现此目标的正确方法。那么如何实现可嵌入在QML中的自定义C ++项目并将其用作简单的绘图区域呢?