playimage.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "playimage.h"
  2. #include <QPainter>
  3. PlayImage::PlayImage(QWidget *parent) : QWidget(parent)
  4. {
  5. // 适用调色板设置背景色
  6. QPalette palette(this->palette());
  7. palette.setColor(QPalette::Window, Qt::black); //设置背景黑色
  8. this->setPalette(palette);
  9. this->setAutoFillBackground(true);
  10. }
  11. /**
  12. * @brief 传入Qimage图片显示
  13. * @param image
  14. */
  15. void PlayImage::updateImage(const QImage& image)
  16. {
  17. updatePixmap(QPixmap::fromImage(image));
  18. }
  19. /**
  20. * @brief 传入QPixmap图片
  21. * @param pixmap
  22. */
  23. void PlayImage::updatePixmap(const QPixmap &pixmap)
  24. {
  25. m_mutex.lock();
  26. m_pixmap = pixmap;
  27. m_mutex.unlock();
  28. update();
  29. }
  30. /**
  31. * @brief 使用Qpainter显示图片
  32. * @param event
  33. */
  34. void PlayImage::paintEvent(QPaintEvent *event)
  35. {
  36. if(!m_pixmap.isNull())
  37. {
  38. QPainter painter(this);
  39. #if 0
  40. // 经过粗略测试,QImage先缩放后转为QPixmap的方式在图像比较小时耗时少,图片越大耗时越大
  41. QPixmap pixmap = QPixmap::fromImage(m_image.scaled(this->size(), Qt::KeepAspectRatio));
  42. // 先将QImage转换为QPixmap再进行缩放则耗时比较少,并且稳定,不会因为缩放图片大小而产生太大影响
  43. QPixmap pixmap1 = QPixmap::fromImage(m_image).scaled(this->size(), Qt::KeepAspectRatio);
  44. #endif
  45. m_mutex.lock();
  46. QPixmap pixmap = m_pixmap.scaled(this->size(), Qt::KeepAspectRatio);
  47. m_mutex.unlock();
  48. int x = (this->width() - pixmap.width()) / 2;
  49. int y = (this->height() - pixmap.height()) / 2;
  50. painter.drawPixmap(x, y, pixmap);
  51. }
  52. QWidget::paintEvent(event);
  53. }