在QWidget窗口绘制图片或者色彩。
简单粗暴直接上代码:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void DrawOnePicture(string src, QImage &img);
protected:
void paintEvent(QPaintEvent *event) override;
private:
Ui::MainWindow *ui;
QImage m_img;
};
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
DrawOnePicture(FILENAME, m_img);
update();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::DrawOnePicture(string src, QImage &img)
{
Mat _src = imread(src);
if(_src.empty())
return;
cvtColor(_src, _src, COLOR_BGR2RGB);
//图像比较大的要使用深拷贝
img = QImage(_src.data, _src.cols, _src.rows, _src.step, QImage::Format_RGB888).copy();
}
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
#if 0
QPixmap image = QPixmap::fromImage(m_img);
image = image.scaled(this->width(), this->height(), Qt::IgnoreAspectRatio, Qt::FastTransformation);
painter.drawPixmap(0, 0, image);
#else
painter.fillRect(this->rect(), QBrush(Qt::red));
#endif
}