Qt之一个鼠标和按键响应事件演示

在ui上添加两个控件,分别为lable和pushButton。

在mainwindow.h中添加两个事件:mouseMoveEvent  和  keyPressEvent


实现的功能为:按下键盘z键,显示一张图片

                            按下pushbutton,显示坐标,并将光标自定义一个图标

代码如下:

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtWidgets/QMainWindow>
#include "ui_mainwindow.h"
#include <QMouseEvent>

class MainWindow : public QMainWindow
{
	Q_OBJECT

public:
	MainWindow(QWidget *parent = 0);
	~MainWindow();

public:
	void mouseMoveEvent(QMouseEvent *);
	void keyPressEvent(QKeyEvent *);

private:
	Ui::MainWindowClass ui;
};

#endif // MAINWINDOW_H

//mianwindow.cpp
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	ui.label->setText(tr("push the key: z"));
	ui.pushButton->setText(tr("try to press the mouse and to move "));
}

MainWindow::~MainWindow()
{

}

void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
	QCursor my(QPixmap("C:/Users/sony/Desktop/practice/1/Win32/Debug/bubble.png"));
	QApplication::setOverrideCursor(my);
	int x = e->pos().x();
	int y = e->pos().y();

	ui.pushButton->setText(tr("mouse:(%1,%2)").arg(x).arg(y));
    ui.pushButton->move(e->pos());
}

void MainWindow::keyPressEvent(QKeyEvent *e)
{
	if(e->key() == Qt::Key_Z)
	{
		ui.label->setPixmap(QPixmap("C:/Users/sony/Desktop/pic/Lena.jpg"));
		ui.label->resize(100, 100);
	}
}

//main.cpp
#include "mainwindow.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	MainWindow w;
	w.show();
	return a.exec();
}


你可能感兴趣的:(Qt之一个鼠标和按键响应事件演示)