使用 CSS (QSS) 选择器获取 QWidget*

Get QWidget* using a CSS (QSS) selector

Qt 允许您使用样式表设置 GUI 的样式。那些使用与常规 CSS 相似的选择器语法。我想在代码中使用这些选择器来访问特定的小部件,类似于 jQuery 的工作方式。例如:

SomeQtCSSMagic::resolveSelector("QPushButton#okButton");

这可能吗?如果没有,是否至少有我可以从 Qt 库复制粘贴并编辑以满足我的需要的代码?

目前,Qt 没有为此提供官方支持。但是使用普通的 C++ 代码并不难。

您的选择器转换为:

for (auto top : qApp->topLevelWidgets()) {
  auto widgets = top->findChildren<QWidget*>("okButton");
  widgets << top;
  for (auto widget : widgets)
    if (widget->inherits("QPushButton"))
      qDebug() << "found" << widget;
}

如果你觉得这样的代码很乏味,你可以利用私有Qt代码。 CSS 解析器接口在 src/gui/text/qcssparser_p.h. Apart from the parser, you also need some code to use the parsed selector to find the widget. Namely, you have to implement a QCss::StyleSelector for a node that points to a QObject. That's done by QStyleSheetStyleSelector in src/widgets/styles/qstylesheetstyle.cpp 中,但这是一个未导出的本地 class,因此您确实有一些 copypasta 来处理它。

一旦您实现了 QCss::StyleSelector,此处为 QObjectStyleSelector,获取选择器应用的小部件就很容易了。您必须遍历所有小部件,并查看 CSS 机制是否对给定节点有任何规则,假设一个虚拟样式表由您的选择器和一个空主体 {} 组成。这种方法支持样式表支持的所有选择器,但在小部件的样式上进行选择除外:

QWidgetList select(const QString & selector) {
   static QHash<QString, StyleSheet> cache;
   QWidgetList result;
   QObjectStyleSelector oSel;
   auto it = cache.find(selector);
   if (it == cache.end()) {
      StyleSheet styleSheet;
      Parser parser(selector + "{}");
      if (!parser.parse(&styleSheet))
         return result;
      it = cache.insert(selector, styleSheet);
   }
   oSel.styleSheets.append(*it);

   for (auto top : qApp->topLevelWidgets()) {
      auto widgets = top->findChildren<QWidget*>();
      widgets << top;
      for (auto widget : widgets) {
         StyleSelector::NodePtr n { widget };
         auto rules = oSel.styleRulesForNode(n);
         if (!rules.isEmpty()) result << widget;
      }
   }
   return result;
}

上面的代码不是 "distracted" 小部件上可能存在的任何样式表 - 它考虑了它们的副作用(例如 属性 更改),但忽略它们。

您可以按如下方式测试:

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QDialog dialog;
   QPushButton button{"OK", &dialog};
   button.setObjectName("okButton");
   button.setStyleSheet("color: red");

   auto dialog_l = QWidgetList() << &dialog;
   auto button_l = QWidgetList() << &button;
   auto all_l = button_l + dialog_l;
   Q_ASSERT(select("QPushButton#okButton") == button_l);
   Q_ASSERT(select("QDialog QPushButton") == button_l);
   Q_ASSERT(select("QDialog") == dialog_l);
   Q_ASSERT(select("QDialog, QPushButton") == all_l);
}

copy-pasta在上面之前:

// https://github.com/KubaO/Whosebugn/tree/master/questions/css-selector-35129103
#include <QtWidgets>
#include <private/qcssparser_p.h>

using namespace QCss;

// FROM src/widgets/styles/qstylesheetstyle.cpp

#define OBJECT_PTR(node) (static_cast<QObject*>((node).ptr))

static inline QObject *parentObject(const QObject *obj)
{
   if (qobject_cast<const QLabel *>(obj) && qstrcmp(obj->metaObject()->className(), "QTipLabel") == 0) {
      QObject *p = qvariant_cast<QObject *>(obj->property("_q_stylesheet_parent"));
      if (p)
         return p;
   }
   return obj->parent();
}

class QObjectStyleSelector : public StyleSelector
{
public:
   QObjectStyleSelector() { }

   QStringList nodeNames(NodePtr node) const Q_DECL_OVERRIDE
   {
      if (isNullNode(node))
         return QStringList();
      const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
#ifndef QT_NO_TOOLTIP
      if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
         return QStringList(QLatin1String("QToolTip"));
#endif
      QStringList result;
      do {
         result += QString::fromLatin1(metaObject->className()).replace(QLatin1Char(':'), QLatin1Char('-'));
         metaObject = metaObject->superClass();
      } while (metaObject != 0);
      return result;
   }
   QString attribute(NodePtr node, const QString& name) const Q_DECL_OVERRIDE
   {
      if (isNullNode(node))
         return QString();

      auto obj = OBJECT_PTR(node);
      auto value = obj->property(name.toLatin1());
      if (!value.isValid()) {
         if (name == QLatin1String("class")) {
            auto className = QString::fromLatin1(obj->metaObject()->className());
            if (className.contains(QLatin1Char(':')))
               className.replace(QLatin1Char(':'), QLatin1Char('-'));
            return className;
         }
      }
      if(value.type() == QVariant::StringList || value.type() == QVariant::List)
         return value.toStringList().join(QLatin1Char(' '));
      else
         return value.toString();
   }
   bool nodeNameEquals(NodePtr node, const QString& nodeName) const Q_DECL_OVERRIDE
   {
      if (isNullNode(node))
         return false;
      auto metaObject = OBJECT_PTR(node)->metaObject();
#ifndef QT_NO_TOOLTIP
      if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
         return nodeName == QLatin1String("QToolTip");
#endif
      do {
         const ushort *uc = (const ushort *)nodeName.constData();
         const ushort *e = uc + nodeName.length();
         const uchar *c = (const uchar *)metaObject->className();
         while (*c && uc != e && (*uc == *c || (*c == ':' && *uc == '-'))) {
            ++uc;
            ++c;
         }
         if (uc == e && !*c)
            return true;
         metaObject = metaObject->superClass();
      } while (metaObject != 0);
      return false;
   }
   bool hasAttributes(NodePtr) const Q_DECL_OVERRIDE
   { return true; }
   QStringList nodeIds(NodePtr node) const Q_DECL_OVERRIDE
   { return isNullNode(node) ? QStringList() : QStringList(OBJECT_PTR(node)->objectName()); }
   bool isNullNode(NodePtr node) const Q_DECL_OVERRIDE
   { return node.ptr == 0; }
   NodePtr parentNode(NodePtr node) const Q_DECL_OVERRIDE
   { NodePtr n; n.ptr = isNullNode(node) ? 0 : parentObject(OBJECT_PTR(node)); return n; }
   NodePtr previousSiblingNode(NodePtr) const Q_DECL_OVERRIDE
   { NodePtr n; n.ptr = 0; return n; }
   NodePtr duplicateNode(NodePtr node) const Q_DECL_OVERRIDE
   { return node; }
   void freeNode(NodePtr) const Q_DECL_OVERRIDE
   { }
};

// END FROM
#cssparser-35129103.pro
QT = widgets gui-private
CONFIG += c++11
TARGET = cssparser-35129103
TEMPLATE = app
SOURCES += main.cpp