c++ - 在 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 画布本身上绘图并不合适,因为绘图是使用计算进行的)
解决方案
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 完成类似的解决方案。
推荐阅读
- javascript - 状态改变时不调用函数
- django - 在 Django 模板中为应用程序名称 {% url %} 使用变量
- javascript - JavaScript 按名称排序数组
- apache-spark - 从嵌套数组/结构中查询字段
- google-cloud-platform - Google Cloud Storage 传输接收器前缀
- javascript - 如何在不使用内置 .repeat() 的情况下重复给定次数的字符串?
- java - 如何使用 API Gateway 代理在 AWS Lambda 中将多个文件作为多部分请求处理?
- excel - VBA 运行时错误 76 - 在 Excel 中找不到路径
- amazon-web-services - 使用 CloudFormation 模板在 Amazon S3 Glacier 中创建文件库
- javascript - 在 Gitlab Servicedesk 功能中将收集的电子邮件作为新票证/问题发送