在QT creator 中如何将在窗口中绘制的内容保存为图片
时间: 2024-02-03 21:11:38 浏览: 130
在QT Creator中将窗口中绘制的内容保存为图片,可以借助QPixmap和QPainter来完成。
具体步骤如下:
1. 在窗口类中定义一个QPixmap对象和一个绘图标志位flag:
```cpp
class MyWindow : public QWidget
{
Q_OBJECT
public:
MyWindow(QWidget *parent = 0);
~MyWindow();
private:
QPixmap pixmap; //定义一个QPixmap对象
bool flag; //定义一个绘图标志位
...
}
```
2. 在窗口的paintEvent()函数中进行绘制:
```cpp
void MyWindow::paintEvent(QPaintEvent *)
{
QPainter painter(this);
if(flag)
{
painter.drawPixmap(0, 0, pixmap);
}
else
{
//绘制内容
...
}
}
```
3. 在窗口的mousePressEvent()函数中设置绘图标志位为true:
```cpp
void MyWindow::mousePressEvent(QMouseEvent *event)
{
flag = true;
pixmap.fill(Qt::white); //清空QPixmap对象
update(); //强制刷新窗口
}
```
4. 在窗口的mouseReleaseEvent()函数中设置绘图标志位为false,并保存QPixmap对象为图片文件:
```cpp
void MyWindow::mouseReleaseEvent(QMouseEvent *event)
{
flag = false;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("Images (*.png *.xpm *.jpg)")); //选择保存文件路径
if(!fileName.isEmpty())
{
pixmap.save(fileName);
}
}
```
完整代码示例:
```cpp
#include <QtWidgets>
class MyWindow : public QWidget
{
Q_OBJECT
public:
MyWindow(QWidget *parent = 0);
~MyWindow();
protected:
void paintEvent(QPaintEvent *);
void mousePressEvent(QMouseEvent *);
void mouseReleaseEvent(QMouseEvent *);
private:
QPixmap pixmap;
bool flag;
};
MyWindow::MyWindow(QWidget *parent)
: QWidget(parent)
{
flag = false;
}
MyWindow::~MyWindow()
{
}
void MyWindow::paintEvent(QPaintEvent *)
{
QPainter painter(this);
if(flag)
{
painter.drawPixmap(0, 0, pixmap);
}
else
{
//绘制内容
painter.setPen(Qt::red);
painter.setFont(QFont("Arial", 30));
painter.drawText(rect(), Qt::AlignCenter, "Hello, world!");
}
}
void MyWindow::mousePressEvent(QMouseEvent *event)
{
flag = true;
pixmap.fill(Qt::white);
update();
}
void MyWindow::mouseReleaseEvent(QMouseEvent *event)
{
flag = false;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("Images (*.png *.xpm *.jpg)"));
if(!fileName.isEmpty())
{
pixmap.save(fileName);
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWindow w;
w.show();
return app.exec();
}
#include "main.moc"
```
运行程序后,单击窗口并拖动鼠标绘制任意图形,松开鼠标后会弹出文件保存对话框,选择保存的文件路径和格式即可将绘制的内容保存为图片。
阅读全文