qt如何实现画图板的各项功能(如:新建画布,打开图片,选择画笔颜色和粗细,橡皮擦,填充颜色等)
时间: 2024-04-09 13:33:34 浏览: 110
在 Qt 中实现一个画图板的功能可以通过使用 QWidget 或者 QGraphicsView 进行绘图,以及使用各种控件和信号槽来实现不同的功能。下面是一个简单的示例,展示了如何实现画图板的一些基本功能:
```cpp
#include <QtWidgets>
class DrawingBoard : public QWidget {
public:
DrawingBoard(QWidget *parent = nullptr) : QWidget(parent) {
setAttribute(Qt::WA_StaticContents);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setMouseTracking(true);
m_penColor = Qt::black;
m_penWidth = 2;
m_brushColor = Qt::white;
m_eraserMode = false;
}
protected:
void paintEvent(QPaintEvent *event) override {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawImage(rect(), m_image, rect());
}
void mousePressEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
m_lastPoint = event->pos();
}
}
void mouseMoveEvent(QMouseEvent *event) override {
if (!(event->buttons() & Qt::LeftButton))
return;
QPainter painter(&m_image);
painter.setPen(QPen(m_penColor, m_penWidth));
if (m_eraserMode) {
painter.setCompositionMode(QPainter::CompositionMode_Clear);
painter.drawPoint(event->pos());
} else {
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
painter.drawLine(m_lastPoint, event->pos());
m_lastPoint = event->pos();
}
update();
}
void resizeEvent(QResizeEvent *event) override {
if (width() > m_image.width() || height() > m_image.height()) {
int newWidth = qMax(width() + 128, m_image.width());
int newHeight = qMax(height() + 128, m_image.height());
resizeImage(&m_image, QSize(newWidth, newHeight));
update();
}
QWidget::resizeEvent(event);
}
void resizeImage(QImage *image, const QSize &newSize) {
if (image->size() == newSize)
return;
QImage newImage(newSize, QImage::Format_RGB32);
newImage.fill(m_brushColor);
QPainter painter(&newImage);
painter.drawImage(QPoint(0, 0), *image);
*image = newImage;
}
private:
QImage m_image;
QPoint m_lastPoint;
QColor m_penColor;
int m_penWidth;
QColor m_brushColor;
bool m_eraserMode;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget window;
QVBoxLayout layout(&window);
DrawingBoard drawingBoard;
layout.addWidget(&drawingBoard);
QPushButton newButton("New");***
阅读全文