呜啊呜wuawu
2021-05-11 11:57
采纳率: 66.7%
浏览 81

QT在Widget上绘制图片

刚学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;
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • qfl_sdu 2021-05-11 13:54
    已采纳

    MyWidget类修改如下,如有帮助,忘采纳,谢谢。

    Mywidget.h如下:

    class MyWidget : public QWidget
    {
    public:
        MyWidget(QWidget* parent = 0);
        void setImage(QString name);
    protected:
        void paintEvent(QPaintEvent*);
        
    private:
        QImage image;
    };

    Mywidget.cpp如下

    #include "MyWidget.h"
    #include <QPainter>
    MyWidget::MyWidget(QWidget* parent):QWidget(parent)
    {
    }
     
    void MyWidget::paintEvent(QPaintEvent*)
    {
        QPainter painter(this);
        painter.drawImage(QRectF(0, 0, width(), height()),image);
    }
     
    void MyWidget::setImage(QString name)
    {
        if(!name.isEmpty())
        {
            image.load(name);
            update(); //调用paintEvent重绘,缺了这句话不会重绘的
        } 
    }
    评论
    解决 1 无用
    打赏 举报
  • 查看更多回答(3条)

相关推荐 更多相似问题