[Qt学习笔记]Qt实现鼠标点击或移动时改变鼠标的样式以及自定义鼠标样式

1、鼠标样式介绍以及对应函数

在Qt中大概有20种左右的内置鼠标样式,一般使用setCursor(Qt::CursorShape shape)来进行设置,一般常用的有标准箭头、手型,双箭头等等形状,对于不同的操作系统下,鼠标的样式显示会略有差别,Qt内置的鼠标样式(CursorShape)如下:

2、在鼠标事件中调用鼠标样式设置函数

复制代码
 this->setMouseTracking(true);      //设置为不按下鼠标键触发moveEvent
 void mouseMoveEvent(QMouseEvent* event)
 {
     QPoint mousepos = event()->pos();
 
     //在坐标(0 ~ width,0 ~ height)范围内改变鼠标形状
     if(mousepos.rx() > 0 
        && mousepos.rx() < width
        && mousepos.ry() > 0
        && mousepos.ry() < height)
     {
            this->setCursor(Qt::CrossCursor);
     }
     else
     {
         this->setCursor(Qt::ArrowCursor);      //范围之外变回原来形状
     }
 }

这里通过setMouseTracking(true);这个函数来进行鼠标的跟随操作,当鼠标移动事件触发后判断进行鼠标样式的更改。

3、使用图片自定义鼠标样式

使用函数QCursor::QCursor(const QBitmap & bitmap, const QBitmap & mask, int hotX = -1, int hotY = -1),需要准备自定义鼠标样式的图片和自定义鼠标样式的掩码图片,hotX和hotY设置鼠标热点。甚至可以生成与背景具有反差效果的鼠标样式。该函数详细使用说明如下:

复制代码
CustomCursor::CustomCursor(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	QBitmap bitmap("bitmap.png"); //背景透明的png格式图片
	QBitmap bitmap_mask("bitmap_mask.png");

	QCursor cursor(bitmap, bitmap_mask, -1, -1); //-1 -1表示鼠标热点在中心点
	setCursor(cursor); //设置自定义的鼠标样式
}
相关推荐
xcyxiner2 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner3 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner3 天前
DicomViewer (添加模型类)3
qt
xcyxiner4 天前
DicomViewer (目录调整) 2
qt
xcyxiner4 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能6 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G6 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
森G6 天前
77、线程池原理和实现------服务器源码解析----云视频服务项目
服务器·c++·qt
森G6 天前
71、打包发布---------打包发布
c++·qt
初圣魔门首席弟子6 天前
Node.js 详细介绍(知识库版)
windows·qt·node.js·知识库