为什么在继承 QWidget 和使用 Q_OBJECT 时样式表不起作用? [英] Why do stylesheets not work when subclassing QWidget and using Q_OBJECT?

查看:31
本文介绍了为什么在继承 QWidget 和使用 Q_OBJECT 时样式表不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例 1:使用 Q_OBJECT 创建 QWidget 的子类并设置样式表 -- 无效.

Case 1: Create subclass of QWidget with Q_OBJECT and set stylesheet -- no effect.

案例 2:在没有 Q_OBJECT 的情况下创建 QWidget 的子类并设置样式表 -- 按预期工作

Case 2: Create subclass of QWidget without Q_OBJECT and set stylesheet -- works as expected

案例 3:使用 Q_OBJECT 创建 QLabel 的子类并设置样式表 -- 按预期工作

Case 3: Create subclass of QLabel with Q_OBJECT and set stylesheet -- works as expected

如何理解这种行为?是否可以在案例 1 中使用样式表?

How to understand this behavior? Is it possible to make stylesheets work in the case 1?

推荐答案

如果希望自定义 QWidget 子类支持样式表,则需要提供以下代码:Qt代码:

If you want custom QWidget subclasses to support stylesheets, you need to provide the following code: Qt Code:

void myclass::paintEvent(QPaintEvent *pe)
{                                                                                                                                        
  QStyleOption o;                                                                                                                                                                  
  o.initFrom(this);                                                                                                                                                                
  QPainter p(this);                                                                                                                                                                
  style()->drawPrimitive(
    QStyle::PE_Widget, &o, &p, this);                                                                                                                         
};

由 wysota 和 Qt 帮助提供.

Courtesy of wysota, as well as Qt help.

当您不提供 Q_OBJECT 时,您的类没有元数据,因此被视为 QWidget.

When you don't provide Q_OBJECT, your class has no Meta data, and hence is considered as a QWidget.

这篇关于为什么在继承 QWidget 和使用 Q_OBJECT 时样式表不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆