刚学QT,就是重写一个widget类,在这个里面操作,但这个显示图片不知道哪里不对,望指点
MainWindow.h
#pragma once
#include <QtWidgets/QWidget>
#include "ui_MainWindow.h"
#include "MyWidget.h"
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = Q_NULLPTR);
protected slots:
void openFile();
private:
Ui::MainWindowClass ui;
MyWidget* mywidget;
};
MainWindow.cpp
#include "MainWindow.h"
#include <qpainter.h>
#include <qfiledialog.h>
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
mywidget = new MyWidget();
connect(ui.openFile, SIGNAL(clicked()), this, SLOT(openFile()));
}
void MainWindow::openFile()
{
QString curPath = QDir::currentPath();//获取系统当前目录
QString dlgTitle = "选择一张图片"; //对话框标题
QString filter = "图片文件(*.jpg *.png)"; //文件过滤器
QString aFileName = QFileDialog::getOpenFileName(this, dlgTitle, curPath, filter);
if (!aFileName.isEmpty())
mywidget->setImage(aFileName);
}
MyWidget.h
#pragma once
#include <qwidget.h>
#include <qpainter.h>
#include <qimage.h>
#include <qtimer.h>
class MyWidget :
public QWidget
{
public:
MyWidget(QWidget* parent = 0);
void setImage(QString name);
protected:
void paintEvent(QPaintEvent*);
private:
QPainter* painter;
QImage image;
};
MyWidget.cpp
#include "MyWidget.h"
MyWidget::MyWidget(QWidget* parent):QWidget(parent)
{
painter = new QPainter;
}
void MyWidget::paintEvent(QPaintEvent*)
{
painter->begin(this);
painter->drawImage(QRectF(0, 0, width(), height()),image);
painter->end();
}
void MyWidget::setImage(QString name)
{
QImage img;
img.load(name);
if(!img.isNull())
image = img;
}