QT设置鼠标样式

1、使用Qt内置鼠标样式

Qt内置基本的鼠标样式,使用函数QCursor(Qt::CursorShape shape)进行设置。对于不同操作系统来说,设置的Qt鼠标样式会被替换成当前系统支持的鼠标样式效果。

Qt内置的鼠标样式(CursorShape)如下:
在这里插入图片描述
比如设置鼠标样式为Qt::PointingHandCursor:

CustomCursor::CustomCursor(QWidget *parent)
	: QMainWindow(parent)
{
    
    
	ui.setupUi(this);
	setCursor(Qt::PointingHandCursor); //设置鼠标样式
}

效果如下:
在这里插入图片描述

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

使用函数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(32, 32); //生成32x32大小的bitmap图片
	bitmap.fill(Qt::color1); //填充1像素值
	QBitmap bitmap_mask(32, 32); //生成32x32大小的bitmap_mask图片
	bitmap_mask.fill(Qt::color0); //填充0像素值

	QCursor cursor(bitmap, bitmap_mask, -1, -1); //-1 -1表示鼠标热点在中心点
	setCursor(cursor); //设置自定义的鼠标样式
}

效果如下:
在这里插入图片描述

二、使用画图工具生成鼠标样式的图片

为方便理解,这里将颜色设为黑色RGB(0,0,0)表示为1像素值,将颜色设为白色RGB(255,255,255)表示为0像素值。比如生成的bitmap图片:
在这里插入图片描述
生成的bitmap_mask图片:
在这里插入图片描述

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); //设置自定义的鼠标样式
}

效果如下:
在这里插入图片描述

3、使用XPM生成鼠标样式

XPM用于创建位图文件,可生成背景透明的图片。使用函数QPixmap(const char * const xpm[])加载xpm。

static const char* const xpmCursor[] = {
    
    
	// columns rows colors chars-per-pixel
	"20 20 3 1",
	"   c None",
	"=  c #FF796D",   //=的颜色
	"*  c #FFE6B2",   //*的颜色
	"                    ",
	"    =============   ",
	"    =============   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    =============   ",
	"    =============   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    ==*********==   ",
	"    =============   ",
	"    =============   ",
	"                    ",
};

CustomCursor::CustomCursor(QWidget *parent)
	: QMainWindow(parent)
{
    
    
	ui.setupUi(this);
	
	QPixmap pixmap(xpmCursor);
	QCursor cursor(pixmap); //加载xpm生成的图标文件
	setCursor(cursor); //设置自定义的鼠标样式
}

效果如下:
在这里插入图片描述

扫描二维码关注公众号,回复: 12732476 查看本文章

稍加整理方便大家参考,如有错误请指正,谢谢!

猜你喜欢

转载自blog.csdn.net/Staranywhere/article/details/87895321