【问题标题】:How create own qt widget which use qss如何创建自己的使用 qss 的 qt 小部件
【发布时间】:2019-09-13 07:30:27
【问题描述】:

我正在尝试将 qss 用于我自己的小部件。并在加载新样式表时更改样式。我不明白如何从当前样式表中获取颜色。以及何时更新。

要获取颜色,我正在尝试使用 palette().color(QPalette::ColorRole::)。并在 changeEvent 发生时更新它:

class Widget : public QWidget {
    Q_OBJECT
public:
    Widget(QWidget* parent = nullptr)
        : QWidget(parent), primary(this), background(this) {
            update_brushs();
        }

protected:
    void paintEvent(QPaintEvent* event) {
        background.drawRect(event->rect());
        primary.drawText(event->rect(), "hi");

    }

    void changeEvent(QEvent* event) {
        if (event->type() == QEvent::StyleChange) {
            update_brushs();
        }
        QWidget::changeEvent(event);
    }

private:
    void update_brushs() {
        primary.setBrush(palette().color(QPalette::ColorRole::WindowText));
        background.setBrush(palette().color(QPalette::ColorRole::Background));
    }
    QPainter primary;
    QPainter background;
};

但我有普通的小部件

【问题讨论】:

  • 您为什么使用paintEvent() 重载而不仅仅是样式表?
  • @TheBadger 因为我想用自己的自定义paintEvent创建小部件并通过样式表自定义它。问题是:如何访问样式表的样式(颜色)以及何时需要更新缓存的颜色

标签: qt qt5 qwidget qtstylesheets


【解决方案1】:

如果您的问题与使用样式表更改背景颜色或文本颜色一样基本,那么以下内容应该可以帮助您解决问题。

Widget.h

#pragma once
#include <QWidget>
#include <QStyleOption>
#include <QPainter>

class Widget
  : public QWidget
{
  Q_OBJECT

  public:
    Widget( QWidget* parent = nullptr )
      : QWidget( parent ) {}
    ~Widget() override = default;

    void paintEvent( QPaintEvent* ) override
    {
      QStyleOption opt;
      opt.init( this );
      QPainter p( this );
      style()->drawPrimitive( QStyle::PE_Widget, &opt, &p, this );
    }
};

以上可以用以下文件进行测试:

ma​​in.cpp

#include <QApplication>
#include <QPushButton>
#include <QVBoxLayout>

#include "Widget.h"

int main( int argc, char* argv[] )
{
  QApplication a( argc, argv );
  a.setStyleSheet( "Widget { background-color: blue; }" );

  QWidget one;
  new QVBoxLayout( &one );
  Widget w;
  w.setMinimumSize(200, 200);
  one.show();
  one.layout()->setMargin(20);
  one.layout()->addWidget( &w );

  QPushButton button("Change");
  one.layout()->addWidget( &button );
  QObject::connect(&button, &QPushButton::clicked, &a, [&a](){
    a.setStyleSheet( "Widget { background-color: green; }" );
  });

  return a.exec();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多