Qt 各种图片格式的区别

1. qt多种图片格式区别

qt 有多种图片格式,QPicture、QImage、QPixmap/QBitmap 、OpenGLPaintDevice.

  1. QPicture 用来记录和回放 QPainter 命令,可以持久保存到二进制文件中.

     记录:
     QPicture picture;
     QPainter painter;
     painter.begin(&picture);           // paint in picture
     painter.drawEllipse(10,20, 80,70); // draw an ellipse
     painter.end();                     // painting done
     picture.save("drawing.pic");       // save picture
     //每次调用QPainter::begin()会重围Painter.
    	
     回放:
     QPicture picture;
     picture.load("drawing.pic");           // load picture
     QPainter painter;
     painter.begin(&myImage);               // paint in myImage
     painter.drawPicture(0, 0, picture);    // draw the picture at (0,0)
     painter.end();                         // painting done
    
  2. QPixmap 主要用来在屏幕上显示图片。
  3. QImage 和平台无关,可以对图片进行修改(直接某个像素点的修改)
  4. OpenGLPaintDevice,支持QPainter绘制OpenGL context

  5. SVG的支持

QT支持SVG格式的创建与显示。

创建SVG: QSvgGenerator generator; generator.setFileName(path); generator.setSize(QSize(200, 200)); generator.setViewBox(QRect(0, 0, 200, 200)); generator.setTitle(tr(“SVG Generator Example Drawing”)); generator.setDescription(tr(“An SVG drawing created by the SVG Generator “ “Example provided with Qt.”)); QPainter painter; painter.begin(&generator); displayWidget->paint(painter); painter.end();

Label显示SVG:

QSvgRenderer render;
bool ret = render.load(QString("ball.svg"));
QPixmap* pixmap = new QPixmap(100,100);
QPainter p(pixmap);
render.render(&p);
ui.label_svg->setPixmap(*pixmap);

为什么不能直接在主窗体的子控件上Painter

The drawing capabilities of QPaintDevice are currently 
implemented by the QWidget, QImage, QPixmap,
 QGLPixelBuffer, QPicture, and QPrinter subclasses.

官方文档上提示:

Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent().

QPainter 在 widget 内部 用 paint event绘制:

void SimpleExampleWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(Qt::blue);
    painter.setFont(QFont("Arial", 30));
    painter.drawText(rect(), Qt::AlignCenter, "Qt");
} + **Warning: A paint device can only be painted by one painter at a time.**

一种设备,同一时间只能有一个painter.

QPainter的begine(),end()函数用于只绘制一次的情景中

下面这种方法可以:

ui.label_svg->installEventFilter(this);

bool test::eventFilter( QObject *watched, QEvent *event )
{
	if (watched == ui.label_svg && 
		event->type() == QEvent::Paint)
	{
		QPainter painter2(ui.label_svg);
		painter2.setRenderHint(QPainter::Antialiasing,true);
		painter2.setPen(QColor::fromRgb(0,255,255));

		QSvgRenderer render;
		bool ret = render.load(QString("ball.svg"));
		render.render(&painter2,ui.label_svg->rect());
	}
	return QWidget::eventFilter(watched, event);
}

参考:

  1. my coding.net
  2. 定义
  3. https://www.cnblogs.com/-wang-cheng/p/4973021.html
  4. Qt实现在QLabel上绘制2D图形