本博客的主要目的在于对QT有进一步的了解,单纯只使用QT。
今天小例子主要是打开图片,然后显示出来,并且显示图片的路径。
注意其名称如箭头指示,一个是label_2,一个是pushButton
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(); }
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(); };
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); }
点击打开图片,然后就可以显示如下,并且可以显示图片的路径
当代码第一次写入的时候,这个时候控件的名字下面会出现波浪线,如下。
放上去的时候会显示没有ui没有成员label_2.
这种情况就是ui界面已经定义了控件,但是在cpp里面却没有办法调用。
处理办法如下:
如果不行多试几次。
问题:控件在cpp里面无法调用
https://blog.csdn.net/qq_38378235/article/details/82288874
打开显示图片:
https://blog.csdn.net/weixin_42704090/article/details/90400427
原文:https://www.cnblogs.com/fantianliang/p/12356131.html