Qt qss问题总结

1.在QWidget中设定了setObjectName,就是不起作用。

   解决方法重写paintEvent。

#ifndef BROWSEWIDGET_H
#define BROWSEWIDGET_H

#include <QObject>
#include <QWidget>
#include <QLabel>

class BrowseWidget : public QWidget
{
    Q_OBJECT
public:
    explicit BrowseWidget(QWidget *parent = nullptr);

signals:
protected:
    void paintEvent(QPaintEvent *event);
public slots:
private:
    void initUI();
};

#endif // BROWSEWIDGET_H
#include "browsewidget.h"
#include<QVBoxLayout>
#include<QHBoxLayout>
#include <QStylePainter>
#include <QStyleOption>
BrowseWidget::BrowseWidget(QWidget *parent) : QWidget(parent)
{
    initUI();
    this->setObjectName("BrowseWidget");
}
void BrowseWidget::paintEvent(QPaintEvent *event)
{
    QStylePainter painter(this);
    QStyleOption opt;
    opt.initFrom(this);
    opt.rect=rect();
    painter.drawPrimitive(QStyle::PE_Widget, opt);
    QWidget::paintEvent(event);
}

void BrowseWidget::initUI()
{
    QVBoxLayout *mainVLayout=new QVBoxLayout(this);
    QLabel *lbl=new QLabel("切片浏览");
    mainVLayout->addWidget(lbl);
    setLayout(mainVLayout);
}

 Qt帮助下对此问题说明

Supports only the background, background-clip and background-origin properties.
If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:

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

The above code is a no-operation if there is no stylesheet set.
Warning: Make sure you define the Q_OBJECT macro for your custom widget.
原文地址:https://www.cnblogs.com/ike_li/p/11493443.html