天天看点

qlabel 显示图片后大小不变_图形编程:QT使用scrollarea显示图片的解决方案需求:

qlabel 显示图片后大小不变_图形编程:QT使用scrollarea显示图片的解决方案需求:

需求:

在界面上点击“显示图片”按钮,会调用scrollarea窗口显示图片,窗口大小能根据图片大小自动调整,但是最大为1024*768,图片过大就要有滚动条来显示

IDE环境:

QT Creator ,linux ,ubuntu12.04

代码:

mainwindow中点击“显示图片”调用scrollarea窗口,下面的函数是被一个按钮的槽函数调用的

void MainWindow::Show_Image_byname(char *filename){ if(!filename || !strlen(filename)) { return; } char buf[128]= {0}; strcpy(buf,SAVE_IMAGE); strcat(buf,filename); ScrollArea *new_image = new ScrollArea(); new_image->set_image(buf); new_image->setBackgroundRole(QPalette::Dark); new_image->show(); return;}
           

添加文件scrollarea.ui文件,画出一个scrollarea

qlabel 显示图片后大小不变_图形编程:QT使用scrollarea显示图片的解决方案需求:

在生成的scrollarea.h中添加私有成员QLabel

private: Ui::ScrollArea *ui; QLabel * label;
           

在析构函数中添加内存释放

ScrollArea::~ScrollArea(){ delete ui; if(label) { delete label; }}
           

在生成的scrollarea.cpp中添加图片显示实现函数

void ScrollArea::set_image(char *filename){ QImage *ppm = new QImage(filename); label = new QLabel(); printf("ppm->width()=%d, ppm->height()=%d",ppm->width(), ppm->height()); //获取图片的宽度和高度 label->setPixmap(QPixmap::fromImage(*ppm)); this->setWidget(label); /*设置窗口最大高度和宽度为1024*768*/ this->setMaximumHeight(768); this->setMaximumWidth(1024); this->resize(QSize( ppm->width()+5, ppm->height() +5)); return;}
           

继续阅读