首页 > 解决方案 > 在 QQuickPaintedItem 上用鼠标绘制

问题描述

我有这个代码

class cCanvas : public QQuickPaintedItem
..
..
void cCanvas::paint(QPainter *ppainter)
{
    ppainter->setPen(QPen(colorValue()));
    ppainter->drawLine(0, 0, rand() % 255 ,100);
}

QML

MultiPointTouchArea {
    onPressed {
        canvas.update();
    }
}

它可以工作,但是在绘制每条新线时,画布被清除,上一行被删除。但我希望这些线路保持不变。

QML Canvas 有 requestPaint();

如何为 QQuickPaintedItem 调用此方法?

如何在 QQuickPaintedItem 上正确创建用鼠标绘制的能力?

(由于工作速度的原因,在 QML 画布本身上绘图并不合适,因为绘图是使用计算进行的)

标签: c++qtqml

解决方案


Qt 不会缓存已绘制的内容,因此您只能看到最后绘制的内容。一种可能的解决方案是将行指令保存在 QPainterPath 中:

#ifndef CCANVAS_H
#define CCANVAS_H

#include <QPainterPath>
#include <QQuickPaintedItem>

class CCanvas : public QQuickPaintedItem
{
    Q_OBJECT
    Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
    QML_ELEMENT
public:
    CCanvas(QQuickItem *parent = nullptr);
    Q_INVOKABLE void requestPaint();
    void paint(QPainter *painter);
    const QColor &color() const;
    void setColor(const QColor &newColor);

signals:
    void colorChanged();

private:
    QPainterPath m_path;
    QColor m_color;
};

#endif // CCANVAS_H
#include "ccanvas.h"

#include <QPainter>

CCanvas::CCanvas(QQuickItem *parent):QQuickPaintedItem(parent)
{

}

void CCanvas::requestPaint()
{
    QPointF start(0, 0);
    QPointF end(rand() % 255, 100);
    m_path.moveTo(start);
    m_path.lineTo(end);
    update();
}

void CCanvas::paint(QPainter *painter)
{
    painter->setPen(QPen(m_color));
    painter->drawPath(m_path);
}

const QColor &CCanvas::color() const
{
    return m_color;
}

void CCanvas::setColor(const QColor &newColor)
{
    if (m_color == newColor)
        return;
    m_color = newColor;
    emit colorChanged();
    update();
}
import QtQuick 2.12
import QtQuick.Window 2.12
import Canvas 1.0

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    CCanvas{
        id: canvas
        anchors.fill: parent
        color: "red"
    }

    Timer {
        interval: 500; running: true; repeat: true
        onTriggered: canvas.requestPaint()
    }
}
QT += quick

CONFIG += c++11
SOURCES += \
        ccanvas.cpp \
        main.cpp

HEADERS += \
        ccanvas.h

RESOURCES += qml.qrc

CONFIG += qmltypes
QML_IMPORT_NAME = Canvas
QML_IMPORT_MAJOR_VERSION = 1

可以使用 QImage 完成类似的解决方案。


推荐阅读