【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.总结:

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

相关推荐
qq_4017004119 小时前
Qt Positioning 模块访问设备地理位置信息
开发语言·qt
闫有尽意无琼21 小时前
银河麒麟v11 arm编译Qt creator8.0.2报错
开发语言·qt
lqj_本人21 小时前
鸿蒙Qt触控疑云:事件传递丢失与坐标偏移修复
qt·华为·harmonyos
_OP_CHEN21 小时前
从零开始的Qt开发指南:(五)Qt 常用控件之 QWidget(上):解锁 Qt 界面开发的核心基石
开发语言·c++·qt·前端开发·qwidget·gui开发·qt常用控件
happyjoey2171 天前
使用Qt自带的Maintenance Tool将Qt6.9升级为QT6.10
开发语言·qt
lqj_本人1 天前
鸿蒙Qt生命周期:后台被杀后的数据自救
qt·华为·harmonyos
爱码小白2 天前
PyQt5 QTimer总结
开发语言·qt
Jay Chou why did2 天前
13. Qt深入 样式表继承规则
qt
友友马2 天前
『Qt』多元素控件
开发语言·qt
共享家95272 天前
QT-界面优化(中)
开发语言·qt