写了个小demo; QVariant 作为函数参数时候, 实际传入QImage,看起来是QVariant将QImage做了隐式转换一样(可能是qt的元对象做了某些处理);
1 .h中声明 QImage image;
2 cpp添加图片到image
3 函数initQimage 接受image 并返回
4 paintEvent打印出了 QVariant将QImage转换后的图片
//.h
class Form_m : public QWidget
{
Q_OBJECT
public:
explicit Form_m(QWidget *parent = nullptr);
~Form_m();
virtual void paintEvent(QPaintEvent *event);
QImage initQimage(const QVariant &data);
private:
Ui::Form_m *ui;
QImage image;
};
//.cpp
Form_m::Form_m(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Form_m)
{
ui->setupUi(this);
QPushButton *btn = new QPushButton("添加图片",this);
connect(btn,&QPushButton::clicked,this,[=](){
QString imagePath = QFileDialog::getOpenFileName(nullptr,
QObject::tr("选择图片文件"),
"C:/",
QObject::tr("图片文件 (*.png
*.jpg *.jpeg *.bmp)"));
image.load(imagePath);
update();
});
}
void Form_m::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QImage mimage = initQimage(image);//传入image 实际参数是QVariant
painter.drawImage(rect(),mimage);
}
QImage Form_m::initQimage(const QVariant &data)
{
QImage image2 = data.value<QImage>();
return image2;
}