平台windows 7,Qt 4
.h:
#ifndef KEYBOARDEVENTTEST1_H
#define KEYBOARDEVENTTEST1_H
#include <QtGui/QWidget>
#include <QKeyEvent>
#include <QPaintEvent>
#include <QPixmap>
#include <QImage>
#include <QPainter>
#include <QPen>
#include <QPoint>
#include "ui_keyboardeventtest1.h"
class KeyboardEventTest1 : public QWidget
{
Q_OBJECT
public:
KeyboardEventTest1(QWidget *parent = 0, Qt::WFlags flags = 0);
~KeyboardEventTest1();
void drawPix();
void keyPressEvent(QKeyEvent *);
void paintEvent(QPaintEvent *);
private:
Ui::KeyboardEventTest1Class ui;
private:
QPixmap *pix;
QImage image;
int startX;
int startY;
int width;
int height;
int step;
};
#endif // KEYBOARDEVENTTEST1_H
.cpp
#include "keyboardeventtest1.h"
KeyboardEventTest1::KeyboardEventTest1(QWidget *parent, Qt::WFlags flags)
:QWidget(parent)
{
setWindowTitle(tr("Key Event"));
setAutoFillBackground(true);
QPalette palette = this->palette();
palette.setColor(QPalette::Window,Qt::white);
setPalette(palette);
setMinimumSize(512,256);
setMaximumSize(512,256);
width=size().width();
height=size().height();
pix = NULL;
pix = new QPixmap(width,height);
pix->fill(Qt::white);
step=32;
image.load("a.jpg");
startX=0;
startY=0;
drawPix();
}
KeyboardEventTest1::~KeyboardEventTest1()
{
}
void KeyboardEventTest1::drawPix()
{
pix->fill(Qt::white);
QPainter painter(pix);
QPen pen(Qt::DotLine);
painter.setPen(pen);
for(int i=step;i<width;)
{
painter.drawLine(QPoint(i,0),QPoint(i,height));
i=i+step;
}
for(int j=step;j<height;)
{
painter.drawLine(QPoint(0,j),QPoint(width,j));
j=j+step;
}
painter.drawImage(QPoint(startX,startY),image);
}
void KeyboardEventTest1::keyPressEvent(QKeyEvent *event)
{
if(event->modifiers() == Qt::ControlModifier)
{
if(event->key() == Qt::Key_Left)
{
startX=(startX-1<0)?startX:startX-1;
}
if(event->key() == Qt::Key_Right)
{
startX=(startX+1+image.width ()>width)?startX:startX+1;
}
if(event->key() == Qt::Key_Up)
{
startY=(startY-1<0)?startY:startY-1;
}
if(event->key() == Qt::Key_Down)
{
startY=(startY+1+image.height()>height)?startY:startY+1;
}
}
else
{
startX=startX-startX%step;
startY=startY-startY%step;
if(event->key() == Qt::Key_Left)
{
startX=(startX-step<0)?startX:startX-step;
}
if(event->key() == Qt::Key_Right)
{
startX=(startX+step+image.width()>width)?startX:startX+step;
}
if(event->key() == Qt::Key_Up)
{
startY=(startY-step<0)?startY:startY-step;
}
if(event->key() == Qt::Key_Down)
{
startY=(startY+step+image.height()>height)?startY:startY+step;
}
if(event->key() == Qt::Key_Home)
{
startX=0;
startY=0;
}
if(event->key() == Qt::Key_End)
{
startX=width-image.width();
startY=height-image.height();
}
}
drawPix();
update();
}
void KeyboardEventTest1::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.drawPixmap(QPoint(0,0),*pix);
}
问题出现在drawPix()函数中,
如果QPainter painter(pix);换成QPainter *painter = new QPainter(pix);的话,在屏幕第一次显示的时候,能够显示出正确的界面,但是当用户按ctrl和向左等箭头的时候,屏幕上就什么都不显示。如果使用QPainter painter(pix);就什么问题都没有,都能正常显示,想知道这是什么问题?!
------解决方案--------------------
new 完,你 delete 了吗?