如果你希望实现实时画线的功能,你可以修改 mouseMoveEvent
的逻辑来在鼠标移动过程中实时绘制贝塞尔曲线。以下是一个修改后的代码示例:
#include <QtWidgets>
class Whiteboard : public QWidget {
public:
Whiteboard(QWidget *parent = nullptr) : QWidget(parent), isDrawing(false) {
setAttribute(Qt::WA_StaticContents);
image = QImage(size(), QImage::Format_RGB32);
image.fill(Qt::white);
}
protected:
void paintEvent(QPaintEvent *event) override {
QPainter painter(this);
painter.drawImage(event->rect(), image, event->rect());
}
void mousePressEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
path.moveTo(event->pos());
isDrawing = true;
}
}
void mouseMoveEvent(QMouseEvent *event) override {
if ((event->buttons() & Qt::LeftButton) && isDrawing) {
path.lineTo(event->pos());
QPainter painter(&image);
QPen pen(Qt::black);
pen.setWidth(2);
painter.setPen(pen);
// 绘制当前路径的贝塞尔曲线段
painter.drawPath(path);
// 更新显示
update();
}
}
void mouseReleaseEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton && isDrawing) {
path.lineTo(event->pos());
QPainter painter(&image);
QPen pen(Qt::black);
pen.setWidth(2);
painter.setPen(pen);
// 绘制最终路径的贝塞尔曲线段
painter.drawPath(path);
isDrawing = false;
}
}
private:
QImage image;
bool isDrawing;
QPainterPath path;
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Whiteboard whiteboard;
whiteboard.show();
return app.exec();
}
这段代码中,在 mouseMoveEvent
中添加了实时绘制的逻辑。在鼠标移动过程中,会绘制当前路径的贝塞尔曲线段,并通过调用 update()
来更新显示。
希望这次能满足你对实时画线的需求!如果还有其他问题,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问