#main.c文件
#include “keyevent.h”
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
KeyEvent w;
w.show();
return a.exec();
}
#include “keyevent.h”//头文件
#ifndef KEYEVENT_H
#define KEYEVENT_H
#include
#include
#include
class KeyEvent : public QWidget
{
Q_OBJECT
public:
KeyEvent(QWidget *parent = 0);
~KeyEvent();
void drawPix();
void keyPressEvent(QKeyEvent *);
void paintEvent(QPaintEvent *);
private:
QPixmap *pix;
QImage image;
int startX;
int startY;
int width;
int height;
int step;
};
#endif // KEYEVENT_H
#include “keyevent.cpp”
#include “keyevent.h”
#include
#include
-
KeyEvent::KeyEvent(QWidget *parent)
-
QWidget(parent)
{
setWindowTitle(tr(“键盘事件”));
// setAutoFillBackground(true);
QPalette palette = this->palette();
palette.setColor(QPalette::Window,Qt::white);
setPalette(palette);
setMinimumSize(1024,512);
setMaximumSize(1024,512);
width=size().width();
height=size().height();
qDebug()<<width << height;
pix = new QPixmap(width,height);
pix->fill(Qt::white);
image.load("../image/image.png");
startX=100;
startY=100;
step=20;
drawPix();
resize(512,256);
}
KeyEvent::~KeyEvent()
{
}
void KeyEvent::drawPix()
{
pix->fill(Qt::white);
QPainter *painter = new QPainter;
QPen pen(Qt::DotLine);
for(int i=step;i<width;i=i+step)
{
painter->begin(pix);
painter->setPen(pen);
painter->drawLine(QPoint(i,0),QPoint(i,height));
painter->end();
}
for(int j=step;j<height;j=j+step)
{
painter->begin(pix);
painter->setPen(pen);
painter->drawLine(QPoint(0,j),QPoint(width,j));
painter->end();
}
painter->begin(pix);
painter->drawImage(QPoint(startX,startY),image);
painter->end();
}
void KeyEvent::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 KeyEvent::paintEvent(QPaintEvent *)
{
QPainter painter;
painter.begin(this);
painter.drawPixmap(QPoint(0,0),*pix);
painter.end();
}文章来源:https://www.toymoban.com/news/detail-488079.html
运行效果:
文章来源地址https://www.toymoban.com/news/detail-488079.html
到了这里,关于键盘按键事件 通过键盘上下左右按键移动界面上图标的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!