gpt4 book ai didi

c++ - 按住鼠标按钮时如何绘制?

转载 作者:太空宇宙 更新时间:2023-11-04 15:34:09 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的绘画应用程序 - 它应该在您单击并拖动光标时进行绘制(就像画图一样)。我知道我必须使用 QPainter 但我该如何处理呢?怎么做?任何帮助将非常感激。我尝试通过互联网潜伏,但没有找到太多信息(我通过代码绘制线条等,你启动一个应用程序,它在这里,但我找不到用户绘制东西的例子)。

最佳答案

这是 Jeremy 的代码而不是散文的答案:

// https://github.com/KubaO/stackoverflown/tree/master/questions/simplepaint-39358392
#include <QtWidgets>

// Make a subclass of the QWidget class, so that you can override some of its
// virtual methods
class PaintWidget : public QWidget {
// Create a QPixmap object that you will use to store the bitmap
// that the user will draw [on].
QPixmap m_pixmap;
QPoint m_lastPos;
// Override the paintEvent(QPaintEvent *) [...]
void paintEvent(QPaintEvent *) override {
QPainter painter{this};
painter.drawPixmap(0, 0, m_pixmap);
}
void resizeEvent(QResizeEvent *) override {
// [...] size the QPixmap to be at least as big as the maximum size of the window
// We'll also never let it shrink so as not to lose the already drawn image.
auto newRect = m_pixmap.rect().united(rect());
if (newRect == m_pixmap.rect()) return;
QPixmap newPixmap{newRect.size()};
QPainter painter{&newPixmap};
painter.fillRect(newPixmap.rect(), Qt::white);
painter.drawPixmap(0, 0, m_pixmap);
m_pixmap = newPixmap;
}
// Override the mousePressEvent(QMouseEvent *) [...]
void mousePressEvent(QMouseEvent * ev) override {
m_lastPos = ev->pos();
draw(ev->pos());
}
// Override the mouseMoveEvent(QMouseEvent *) [...]
void mouseMoveEvent(QMouseEvent * ev) override {
draw(ev->pos());
}
void draw(const QPoint & pos) {
QPainter painter{&m_pixmap};
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen({Qt::blue, 2.0});
painter.drawLine(m_lastPos, pos);
m_lastPos = pos;
update();
}
public:
using QWidget::QWidget;
};

int main(int argc, char ** argv) {
QApplication app{argc, argv};
// Create an object of your subclass and call show()
PaintWidget ui;
ui.show();
return app.exec();
}

不必覆盖 mouseReleaseEvent。在小部件中,默认行为是仅在按下鼠标按钮时跟踪鼠标移动。除非按下按钮,否则不会调用 mouseMoveEvent

关于c++ - 按住鼠标按钮时如何绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39358392/

25 4 0
文章推荐: javascript - 如何在 JavaScript 中根据输入字段数值将字符串推送到数组
文章推荐: php - 目标 ="_self"自己神秘地变成了 "_blank"
文章推荐: html - 使用
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com