将qwidget上的当前项目保存为图像
save the current items on qwidget as image
我试图在QWidget
中绘制一些随机颜色的菱形。我想把当前的QWidget
保存为图像。我使用这样的代码:
QPixmap pixmap(this->size()); this->render(&pixmap); pixmap.save("test.png");
问题是render()
似乎再次调用paintEvent
, paintEvent
将用新的随机颜色绘制菱形,这样我总是得到与显示的图像相比保存的不同图像。有人能告诉我如何保存当前的QWidget
吗?提前谢谢。
void Dialog::paintEvent(QPaintEvent *e) {
QPainter painter(this); QRect background(0,0,this->geometry().width(),this->geometry().height()); painter.setBrush( QBrush( Qt::white ) ); painter.setPen( Qt::NoPen ); //QBrush bbrush(Qt::black,Qt::SolidPattern); painter.drawRect(background); int width = this->geometry().width(); int height = this->geometry().height(); //draw rectangles int rec_size=64; int rows=0; int cols=0; rows=floor((double)height/(double)rec_size); cols=floor((double)width/(double)rec_size); QPointF points[4]; // QRect rec(0,0,rec_size,rec_size); for (int i=0;i<floor(rows);i++){ for (int j=0;j<floor(cols);j++){ painter.setBrush( QBrush( colors[rand() % color_size] ) ); //QPainter painter(this); points[0] = QPointF(rec_size*(j),rec_size*(i+0.5)); points[1] = QPointF(rec_size*(j+0.5),rec_size*(i)); points[2] = QPointF(rec_size*(j+1),rec_size*(i+0.5)); points[3] = QPointF(rec_size*(j+0.5),rec_size*(i+1)); painter.drawPolygon(points, 4); } } painter.end();
}
您可以使用布尔类型的类成员变量来检查paintEvent
中是否应该使用随机颜色。还需要一个变量来保存最后使用的颜色的索引:
bool isRandom;
int lastColor;
paintEvent
应该是:
void Dialog::paintEvent(QPaintEvent *e) {
...
if(isRandom)
{
lastColor = rand() % color_size;
painter.setBrush( QBrush( colors[lastColor] ) );
}
else
painter.setBrush( QBrush( colors[lastColor] ) );
...
}
当定期绘制小部件时,该变量为true。当你想保存它的图像时,将变量赋值为false,保存图像并再次赋值为true:
isRandom = false;
QPixmap pixmap(this->size());
this->render(&pixmap);
pixmap.save("test.png");
isRandom = true;
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 欧拉项目#8答案是大以获得有效答案
- 从链接列表c++中删除一个项目
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 既然存在危险,为什么项目要使用-I include开关
- 为什么我的项目没有保存名称中所做的修改
- 使用C++项目将数据保存在磁盘上
- 我应该在哪里保存代码块项目
- 日蚀。不同的工作区。无法保存相同的项目名称
- 如何在Visual Studio中保存默认启动项目
- Visual Studio不保存启动项目和解决方案配置
- 将qwidget上的当前项目保存为图像
- NetBeans 8.0.2中打开的文件保存在项目文件中,因此在GIT中使其脏
- 在浏览项目列表时保存多个项目的数据
- 使用pushButton保存QListWidget项目