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

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

相关推荐
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
范特西.i6 天前
QT聊天项目(8)
开发语言·qt
枫叶丹46 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发6 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun6 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼886 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x6 天前
Qt中使用Zint库显示二维码
qt
谁刺我心6 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
金刚狼887 天前
在qt creator中创建helloworld程序并构建
开发语言·qt
扶尔魔ocy7 天前
【转载】QT使用linuxdeployqt打包
开发语言·qt