在Qt中,Qt给我们列举了n多种鼠标的形状,然而更多的时候我们喜欢以一些别的图片作为鼠标比较有趣.下面有个自定义鼠标的小程序:就和画图一样,每点击一个按钮,鼠标显示不同的样式.
:
主要是使用了QCursor的一个带图片的构造函数,QCursor cursor(QPixmap());然后让QWidget去设置光标即可.
如果用户点击右键,则光标恢复初始状态.
#ifndef C_H
#define C_H
#include <QtWidgets/QMainWindow>
#include "ui_c.h"
#include <QAction>
#include <QMouseEvent>
class c : public QMainWindow
{
Q_OBJECT
public:
c(QWidget *parent = 0);
~c();
protected:
void mousePressEvent(QMouseEvent *event);
private slots:
void showCursorSlot(QAction*);
private:
Ui::cClass ui;
QAction *m_penAction;
QAction *m_brushAction;
QAction *m_eraseAction;
};
#endif // C_H
#include "c.h"
c::c(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
this->setWindowTitle(QString::fromLocal8Bit("自定义鼠标"));
this->setCursor(QCursor(QPixmap("./Resources/normal.png")));
m_penAction = new QAction(this);
m_penAction->setIcon(QIcon("./Resources/pen.png"));
m_brushAction = new QAction(this);
m_brushAction->setIcon(QIcon("./Resources/brush.png"));
m_eraseAction = new QAction(this);
m_eraseAction->setIcon(QIcon("./Resources/erase.png"));
ui.mainToolBar->addAction(m_penAction);
ui.mainToolBar->addAction(m_brushAction);
ui.mainToolBar->addAction(m_eraseAction);
connect(ui.mainToolBar, SIGNAL(actionTriggered(QAction*)), this, SLOT(showCursorSlot(QAction*)));
}
c::~c()
{
}
void c::showCursorSlot(QAction* action)
{
if (action == m_penAction)
{
this->setCursor(QCursor(QPixmap("./Resources/pen.png")));
}
else if (action == m_brushAction)
{
this->setCursor(QCursor(QPixmap("./Resources/brush.png")));
}
else
{
this->setCursor(QCursor(QPixmap("./Resources/erase.png")));
}
}
void c::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton)
{
this->setCursor(QCursor(QPixmap("./Resources/normal.png")));
}
}