如何在QT中为我的类指定样式表

How to specify style sheets for my classes in QT

我有一个class继承自qframe,“darksheetstyle”qss文件是:

    /* (dot) .QFrame  fix #141, #126, #123 */
.QFrame {
  border-radius: 4px;
  border: 1px solid #455364;
  /* No frame */
  /* HLine */
  /* HLine */
}

.QFrame[frameShape="0"] {
  border-radius: 4px;
  border: 1px transparent #455364;
}

.QFrame[frameShape="4"] {
  max-height: 2px;
  border: none;
  background-color: #455364;
}

.QFrame[frameShape="5"] {
  max-width: 2px;
  border: none;
  background-color: #455364;
}

QFrame没有边框,所以我在同一个qss文件中写了我的class qss:

BorderFrame {
  border-radius: 4px;
  border: 2px solid #455364;
  /* No frame */
  /* HLine */
  /* HLine */
}

cpp 代码是:

class ULTRA_PLOT_EXPORT BorderedFrame : public QFrame
    {
        Q_OBJECT
    public:
        explicit BorderedFrame(QWidget* parent) : QFrame(parent)
        {
            setParent(parent);
        }
        ~BorderedFrame() override = default;
        BorderedFrame(const BorderedFrame&) = delete;
        BorderedFrame& operator=(const BorderedFrame&) = delete;
        BorderedFrame(BorderedFrame&&) = delete;
        BorderedFrame& operator=(BorderedFrame&&) = delete;
        void paintEvent(QPaintEvent* event) override
        {
            QStyleOption opt;
            opt.initFrom(this);
            QPainter p(this);
            style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式
        }
    };

那我自己的QFrameclass还是没有边框,怎么解决?

这符合我的预期:

#include <QtWidgets>

class BorderedFrame : public QFrame
{
  Q_OBJECT
public:
  using QFrame::QFrame;
};

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  app.setStyleSheet("BorderedFrame { border-radius: 4px; border: 2px solid #ff0000; }");
  BorderedFrame w;
  w.show();

  return app.exec();
}

#include "main.moc"