自己找的图片太大,在移动的时候不明显,懒得再找图片,所以用了QPainter将图片画在了label上
代码如下
void Widget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QPixmap pix;
pix.load(":img/move.png");//图片的位置
painter.drawPixmap(picLabel->x(),picLabel->y(),picLabel->width(),picLabel->height(),pix);
}
将图片上下左右移动是通过重写keyPressEvent虚方法,在这个方法中捕捉按钮事件,用move移动位置
代码如下
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QPainter>
#include <QKeyEvent>
#include <QDebug>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private:
QLabel *picLabel;
protected:
void paintEvent(QPaintEvent *);
void keyPressEvent(QKeyEvent *event);
void keyReleaseEvent(QKeyEvent *event);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
resize(500, 500);
picLabel = new QLabel(this);
picLabel->setFixedSize(50, 50);
}
//将图片画在label
void Widget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QPixmap pix;
pix.load(":img/move.png");//图片的位置
painter.drawPixmap(picLabel->x(),picLabel->y(),picLabel->width(),picLabel->height(),pix);
}
void Widget::keyPressEvent(QKeyEvent *event)
{
int x = 0;
int y = 0;
switch (event->key()) {
case Qt::Key_Up:
y = picLabel->y() - 10;
if(y > -10)
picLabel->move(picLabel->x(), y);//向上移动就是x不变y减小
break;
case Qt::Key_Down:
y = picLabel->y() + 10;
if(y < this->height() - 40)
{
picLabel->move(picLabel->x(), y);//向下移动是x不变y 变大
}
break;
case Qt::Key_Right:
x = picLabel->x() + 10;
if(x < this->width() - 40)
{
picLabel->move(x, picLabel->y());
}
break;
case Qt::Key_Left:
x = picLabel->x() - 10;
if(x > -10)
picLabel->move(x, picLabel->y());
break;
default:
break;
}
}
void Widget::keyReleaseEvent(QKeyEvent *event)
{
}
Widget::~Widget()
{
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
效果: