三、QT例子-打开一个图片并且显示

一、前言

        本博客的主要目的在于对QT有进一步的了解,单纯只使用QT。

         今天小例子主要是打开图片,然后显示出来,并且显示图片的路径。

二、工程建立

       1、参考前面 博客一QT安装过程里面的例子, 建立一个QT GUI Application

        2、打开.ui文件,然后拖动一个label控件,双击删除内容,然后拖动一个pushButtion, 更改内容为“打开图片”

          

          注意其名称如箭头指示,一个是label_2,一个是pushButton

            3、拖动一个lineText到如下位置:

               

            4、然后保存并且关闭ui文件

            5、建立工程如图(仍然是博客一的工程),配置属性:release x64

            

           7、代码如下:

          main.cpp:

#include "HelloWorld.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    HelloWorld w;
    w.show();
    return a.exec();
}
View Code

         helloWorld.h

#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_HelloWorld.h"
#include <Qlabel>
#include <QLineEdit>
#include <QImage>
#include <QFileInfo>
#include <QFileDialog>
class HelloWorld : public QMainWindow
{
    Q_OBJECT

public:
    HelloWorld(QWidget *parent = Q_NULLPTR);

private:
    Ui::HelloWorldClass ui;
private slots:
    void OpenImg();
};
View Code

        helloWorld.cpp

#include "HelloWorld.h"

HelloWorld::HelloWorld(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    
    connect(ui.pushButton, SIGNAL(clicked(bool)), this, SLOT(OpenImg()));
}
void HelloWorld::OpenImg()
{
    
    QString OpenFile, OpenFilePath;
    QImage image;

    OpenFile = QFileDialog::getOpenFileName(this,
        "please choose an image file",
        "",
        "Image Files(*.jpg *.png *.bmp *.pgm *.pbm);;All(*.*)");
    if (OpenFile != "")
    {
        if (image.load(OpenFile))
        {
            //仅仅只是导入之后的图片仍然是原来的大小,这个时候我们需要缩放
            ui.label_2->setPixmap(QPixmap::fromImage(image).scaled(ui.label_2->size()));
        }
        
    }
    //显示所有的图片路径
    QFileInfo OpenFileInfo;
    OpenFileInfo = QFileInfo(OpenFile);
    OpenFilePath = OpenFileInfo.filePath();
    ui.lineEdit->setText(OpenFilePath);
}
View Code

  8、编译运行

  点击打开图片,然后就可以显示如下,并且可以显示图片的路径

           

 三、遇到问题

          当代码第一次写入的时候,这个时候控件的名字下面会出现波浪线,如下。        

     

         放上去的时候会显示没有ui没有成员label_2.

         这种情况就是ui界面已经定义了控件,但是在cpp里面却没有办法调用。

   处理办法如下:

    1、点击ui文件,然后右键选择编译

          

          

    2、然后选择HelloWorld项目,右键选择重新扫描解决方案

         

        如果不行多试几次。

四、参考博客

        问题:控件在cpp里面无法调用

         https://blog.csdn.net/qq_38378235/article/details/82288874

        打开显示图片:

         https://blog.csdn.net/weixin_42704090/article/details/90400427

猜你喜欢

转载自www.cnblogs.com/fantianliang/p/12356131.html