为了将用 C++ 编写的带有 Qt 库的 GUI 界面转换为 QML,我必须在 QML 中找到 QPainterPath 的替代方法。事实上,目前,在 GUI 界面中绘制了一堆形状,当某些事件发生时,C++ 代码会修改这些对象的颜色。QPainterPath 对象用于存储这些形状。
如果您能告诉我如何在 QML 画布中绘制两个矩形对象,然后如何在 C++ 代码中修改它们的填充颜色,我将不胜感激。
为了将用 C++ 编写的带有 Qt 库的 GUI 界面转换为 QML,我必须在 QML 中找到 QPainterPath 的替代方法。事实上,目前,在 GUI 界面中绘制了一堆形状,当某些事件发生时,C++ 代码会修改这些对象的颜色。QPainterPath 对象用于存储这些形状。
如果您能告诉我如何在 QML 画布中绘制两个矩形对象,然后如何在 C++ 代码中修改它们的填充颜色,我将不胜感激。
正如我在评论中所说,一个选项可能是 Canvas,它具有类似于 QPainterPath 的方法。在下一部分中,我将展示一个示例,其中可以通过生成随机颜色并由 QTimer 调用的方法从 C++ 更改颜色:
主文件
#include <QColor>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTime>
#include <QTimer>
class ColorProvider: public QObject{
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
public:
QColor color() const{
return mColor;
}
void setColor(const QColor &color){
if(color == mColor)
return;
mColor = color;
emit colorChanged(mColor);
}
Q_INVOKABLE void randomColor(){
qsrand((uint)QTime::currentTime().msec());
setColor(QColor(qrand() % 256, qrand() % 256, qrand() % 256));
}
signals:
void colorChanged(const QColor &color);
private:
QColor mColor;
};
#include "main.moc"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
ColorProvider obj;
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &obj, &ColorProvider::randomColor);
timer.start(100);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("colorProvider", &obj);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Canvas {
id:canvas
anchors.fill: parent
onPaint:{
var ctx = canvas.getContext('2d');
ctx.lineWidth = 4
ctx.fillStyle = "orange"
ctx.strokeStyle = "red"
ctx.fillRect(50, 40, 100, 100)
ctx.stroke()
ctx.fill()
ctx.lineWidth = 10
ctx.fillStyle = colorProvider.color
ctx.fillRect(150, 150, 300, 300)
ctx.stroke()
ctx.fill()
ctx.roundedRect(20, 20, 40, 40, 10, 10)
}
}
Connections {
target: colorProvider
onColorChanged: canvas.requestPaint()
}
}
完整的示例可以在以下链接中找到。