【Qt界面优化】QSS样式--伪类选择器

1.伪类选择器概念

  伪类选择器(Pseudo-States),是根据控件所处的某个状态被选择的。例如:按钮被按下,输入框获取到焦点,鼠标移动到某个控件上等。

  • 当状态具备时,控件被选择,样式生效;
  • 当状态不具备时,控件不被选中,样式失效;

使用:的方式定义伪类选择器。

2.常用的伪类选择器

伪类选择器 说明
:hover 鼠标放到了控件上
:pressed 鼠标左键按下时
:focus 获取输入焦点
:enabled 元素处于可用状态时
:checked 被勾选时
:read-only 元素为只读状态时

这些状态可以使用!来取反。例如:!hover就是鼠标离开控件时,:!pressed就是鼠标松开时等。

3.案例

3.1 设置按钮的伪类样式。

1).在界面上创建一个按钮

2).编写main.cpp,创建全局样式

c++ 复制代码
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString style = "";
    style += "QPushButton{color: red;}";
    style += "QPushButton:hover {color:green;}";
    style += "QPushButton:pressed{color:blue;}";
    a.setStyleSheet(style);

    Widget w;
    w.show();
    return a.exec();
}

3).运行程序,可以看到,默认情况下按钮文字是红色的,鼠标移动上去是绿色的,鼠标按下按钮是蓝色的。

3.2 对上述代码实现的效果,使用事件方式实现。

1).创建MyPushButton类,继承自QPushButton类:

2).把生成代码中的构造函数改成带参数QWidget*版本的构造函数(否则无法和Qt Designer生成的代码适配)。

mypushbutton.h文件

c++ 复制代码
#include <QPushButton>

class MyPushButton : public QPushButton
{
public:
    MyPushButton(QWidget* parent);
};

mypushbutton.cpp文件

c++ 复制代码
#include "mypushbutton.h"

MyPushButton::MyPushButton(QWidget* parent)
    :QPushButton(parent)
{

}

3).在界面上创建按钮,并提升为MyPushButton类型

右键按钮,选择"提升为",在下图出现的对话框,填写提升的类名和头文件:

提升完毕后,在右侧对象树这里,就可以看到类型的变化。

4).重写MyPushButton的四个事件处理函数

修改mypushbutton.h文件:

c++ 复制代码
class MyPushButton : public QPushButton
{
public:
    MyPushButton(QWidget* parent);

    void mousePressEvent(QMouseEvent *e);
    void mouseReleaseEvent(QMouseEvent *e);
    void enterEvent(QEvent *e);
    void leaveEvent(QEvent *e);
};

修改mypushbutton.cpp文件:

  • 初始化设为红色;
  • 鼠标进入时设为绿色,离开时还原红色;
  • 鼠标按下时设为蓝色,松开时还原绿色(松开时鼠标还是在按钮里);
c++ 复制代码
MyPushButton::MyPushButton(QWidget* parent)
    :QPushButton(parent)
{
    this->setStyleSheet("QPushButton{color: red;}");
}

void MyPushButton::mousePressEvent(QMouseEvent *e)
{
    this->setStyleSheet("QPushButton{color: blue;}");
}

void MyPushButton::mouseReleaseEvent(QMouseEvent *e)
{
    this->setStyleSheet("QPushButton{color: green;");
}

void MyPushButton::enterEvent(QEvent *e)
{
    this->setStyleSheet("QPushButton{color: green;}");
}

void MyPushButton::leaveEvent(QEvent *e)
{
    this->setStyleSheet("QPushButton{color: red;}");
}

5).运行程序,可以看到效果与伪类选择器效果一样

4.总结:

  实现相同的功能,伪类选择器比事件的方式简单得多。但不能说事件机制就不好,事件可以完成的功能不仅仅是样式的改变,还可以包含其他业务逻辑,这一点是伪类选择器无法替代的。

相关推荐
zlinear数据采集卡27 分钟前
数据采集卡从入门到精通(38):上位机开发实战——Python/QT/LabVIEW的技术选型与分层架构
python·单片机·嵌入式硬件·qt·fpga开发·开源·labview
skr爱码士2 小时前
05_Qt 核心模块概览——Qt Core、Gui、Widgets、Quick 的职责划分
c++·qt·系统架构·客户端
MOONICK3 小时前
QT的UI开发框架
qt·ui
郝学胜-神的一滴3 小时前
Horse3D 游戏引擎研发笔记(七):Clydesdale——从流式日志到多输出订阅
c++·qt·unity·游戏引擎·图形渲染·unreal engine·opengl
丰锋ff16 小时前
基于 Qt 的智慧社区物业管理系统
开发语言·qt
程与留18 小时前
05_Qt 核心模块概览——Qt Core、Gui、Widgets、Quick 的职责划分
c++·qt
buhuizhiyuci19 小时前
【QT-百日筑基篇】修真世界摸爬滚打多年,终于黄天不负有心人,突破炼器中期——常用控件QWight的属性
开发语言·c++·qt·gui·图形化
Littlehero_12120 小时前
QT自定义控件之热换站系统(源码开源)
开发语言·qt
Quz1 天前
QML MouseArea 鼠标拖拽与滚轮缩放
qt
Quz1 天前
QML MouseArea 事件传递、自定义按钮
qt