图像无法使用QPainter drawImage显示

时间:2017-09-19 09:52:39

标签: qt

我的应用程序中的QWidget中有一个QFrame。当我尝试在QFrame中绘制图像时,只有当坐标为(0,0)时才会插入图像,如果它们像(100,100)那样,则不会绘制图像。我为框架创建了一个新类,并在其中实现了paintEvent(QPaintEvent * p)。我在这做什么事吗?

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QFrame>
#include <QPainter>
#include "frame.h"

class frame;
namespace Ui {
    class Widget;
}
class Widget : public QFrame
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
private:
    Ui::Widget *ui;
    frame * f;
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    f = new frame(ui->frame);
    f->show();
}

Widget::~Widget()
{
    delete ui;
}

frame.h

#ifndef FRAME_H
#define FRAME_H

#include <QObject>
#include <QWidget>
#include <QPainter>

class frame : public QWidget
{
    Q_OBJECT
public:
    explicit frame(QWidget *parent = 0);

protected:
    void paintEvent(QPaintEvent *p);

signals:

public slots:
};

#endif // FRAME_H

frame.cpp

#include "frame.h"

frame::frame(QWidget *parent) : QWidget(parent)
{

}

void frame::paintEvent(QPaintEvent *p)
{
    QPainter* pPainter = new QPainter(this);
    QImage img(":/left.png");
    Q_ASSERT(!img.isNull());
    QRect source(0,0,20,10);
    QRect target(50,50,20,10);
    pPainter->drawImage(target, img,source);
    QWidget::paintEvent(p);
    QWidget::update();
}

如果我在上面的代码中使用QRect目标(0,0,20,10),则会绘制图像。

testImage.pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = testImage
TEMPLATE = app

DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += main.cpp\
        widget.cpp \
    frame.cpp

HEADERS  += widget.h \
    frame.h

FORMS    += widget.ui

RESOURCES += \
    src.qrc

DISTFILES +=

我被困在这个很长一段时间,任何想法都会有所帮助。我尝试过Qt版本5.6和5.8,结果相似。操作系统是Lubuntu。图像分辨率为20 * 10。感谢。enter image description here

2 个答案:

答案 0 :(得分:0)

试试这样:

void frame::paintEvent(QPaintEvent *p){
QPainter lPainter(this);
QPixmap lPixmap(":/left.png");
Q_ASSERT(!lPixmap.isNull());
QRect source(0,0,20,10);
QRect target(50,50,20,10);
lPainter->drawPixmap(target, lPixmap);
QWidget::paintEvent(p);}

删除更新表单painEvent并尝试使用pixmap。

答案 1 :(得分:0)

我找到了一个解决方案,我已经将QgraphicsView子类化并重新实现了paint方法,

void graphicsView::paintEvent(QPaintEvent *e)
{
  QGraphicsView::paintEvent(e);
  QPainter pPainter(this->viewport());
  QImage img(":/images/x.png");
  Q_ASSERT(!img.isNull());
  QRect target(300,230,20,10);
  pPainter.drawImage(target, img);
}
相关问题