1. 添加控件所需要的头文件,最好在头文件中添加以下代码
#include <QPushButton>
#include <QImage>
#include <QPixmap>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QLabel>
#include <QImage>
#include <QPainter>
#include <QMessageBox>
2.声明类中控件实例,也可在cpp文件中添加
private:
QPushButton *button; //新建按钮
QLabel *showlabel; //标签显示
QImage *image; //图片
protected:
//void paintEvent(QPaintEvent *); //绘图重绘事件
因为你已经操作了重绘绘图事件,所以这里就不再赘述了
3.cpp执行文件中对控件进行声明和操作
this->resize(300,300); //窗口设置
this->setWindowTitle("text"); //窗口设置
button = new QPushButton(this); //控件初始化
button->setText("图像转换");
button->move(100,150); //设置位置
showlabel = new QLabel(this); //控件初始化
showlabel->setText("text");
showlabel->move(100,250); //设置位置
4.槽函数写法实例方法一
//单个文件处理
connect(button,&QPushButton::clicked,
[=]()
{
QString filename = "../text.jpg"; //文件路径
image = new QImage;
if( ! (image->load(filename)))
{
QMessageBox::information(this,tr("打开图像失败"),tr("打开图像失败!"),
QMessageBox::Yes);
delete image;
return;
}
showlabel->resize(image->width(),image->height()); //设置显示区域为图片大小
showlabel->setPixmap(QPixmap::fromImage(*image)); //区域显示图片
}
);
方法二
connect(button,&QPushButton::clicked,
[=]()
{
QString path = QFileDialog::getOpenFileName(this,"open","../","PNG(*.png)"); //获取路径
if(path.isEmpty() == false)
{
QFile file(path);
bool isOK = file.open(QIODevice::ReadOnly); //只读方式读取
QImage *image = new QImage;
if(isOK == true)
{
showlabel->resize(image->width(),image->height()); //设置显示区域为图片大小
showlabel->setPixmap(QPixmap::fromImage(*image)); //区域显示图片
}
}
}
);