我有一个 qtquick 项目,其中包含一个 main.qml 和一个 EaDrawArea,它继承自 QQuickPaintedItem,并且可以从 main.qml 访问。qml 中有一个 Slider,它绑定到 EaDrawArea 的m_scale(3 到 100),我还设置了一个世界变换矩阵
(m_rate、0.0、0.0、
0.0、-m_rate、0.0、
512.0、384.0、1.0),
m_rate是 EaDrawArea 的成员,它是 1024/20。下面是 main.qml:
Window {
width: 1200
height: 1000
visible: true
title: qsTr("Hello World")
DrawingArea {
id: drawarea
focus: trues
fillColor: "#dddddd"
width: 1024
height: 768
anchors.left: parent.left
anchors.leftMargin: 10
anchors.top: parent.top
anchors.topMargin: 10
MouseArea {
anchors.fill: parent
onPressed: {
drawarea.focus = true
mouse.accepted = false
}
}
}
Slider {
id: scalevalue
height: 50
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
width: parent.width-10
anchors.margins: 5
value: 3.0
stepSize: 1.0
minimumValue: 3.0
maximumValue: 100.0
onValueChanged: {
drawarea.setScaleValue(scalevalue.value)
}
}
}
构造函数, mousePressEvent 和paint函数如下:
EaDrawArea::EaDrawArea(QQuickItem *parent) {
m_scale = 3;
m_rate = 1024.0 / 20.0;
m_x=0;
m_y=0;
m_x1 = 0;
m_y1 = 0;
setAcceptedMouseButtons(Qt::AllButtons);
setAcceptHoverEvents(true);
}
void EaDrawArea::mousePressEvent(QMouseEvent *event)
{
m_x = (event->x() - 512.0) / m_rate; // 512 is half of the canvas width (1024 / 2)
m_y = -(event->y() - 384.0) / m_rate; // 384 is half of the canvas height (768 / 2)
m_x1 = m_x * m_rate / m_scale;
m_y1 = m_y * m_rate / m_scale;
this->update(); // Trigger a repaint to draw at the new coordinates
}
void EaDrawArea::paint(QPainter* painter) {
painter->setRenderHint(QPainter::Antialiasing, true);
QTransform trans;
trans.setMatrix(m_rate, 0.0, 0.0,
0.0, -m_rate, 0.0,
512.0, 384.0, 1.0);
painter->resetTransform();
painter->setWorldTransform(trans);
painter->save();
QPen redPen(Qt::red);
redPen.setWidth(1);
redPen.setCosmetic(true);
painter->setPen(redPen);
QRectF rect(m_x1, m_y1, 10, 5);
QPointF center = rect.center();
//1. painter->translate(center);
painter->scale(m_scale/m_rate, m_scale/m_rate);
//2. painter->translate(-center);
painter->drawRect(rect);
painter->restore();
}
我想在鼠标光标处绘制一个红色矩形,更重要的是从矩形的中心缩放。如果我在 paint 函数中注释掉上面的两行,缩放有效但不从中心开始。如果我取消注释上面的两行,缩放将从中心开始,但矩形不会在鼠标光标处呈现,为什么?如何解决(在光标处渲染并从矩形中心缩放)?有偿100元解决。
--
FROM 120.244.220.*