QPushButton 出来了,我没有设置

问题描述

我在 ubuntu kde 20.04,qt5.15 工作 我的目的是创建一个 QPushButton,当他被点击时改变他的颜色,然后我创建了一个新的派生类来做这个(Facelet),它可以工作,但我得到的颜色不是我假设得到的颜色。

Facelet.h

#ifndef FACELET_H
#define FACELET_H

#include <QPushButton>

class Facelet : public QPushButton
{
    Q_OBJECT
public:
    explicit Facelet(QWidget * parent = nullptr);
    explicit Facelet(int color,QWidget *pareny = nullptr);

    void reset();

    static QString colors[6];

private slots:

    void __change_color();

private:
    int _ColorIndex;
};

#endif // FACELET_H

Facelet.cpp

#include "Facelet.h"

QString Facelet::colors[6] = { "background-color: yellow;","background-color: red;","background-color: green;","background-color: rgb(255,130,50);","background-color: blue;","background-color: white;" };
enum { rxyellow,rxred,rxgreen,rxorange,rxblue,rxwhite };
//public

Facelet::Facelet(QWidget *parent) :
    QPushButton(parent),_ColorIndex(-1)
{
    this->resize(75,75);
    this->setStyleSheet("background-color: gray");
    connect(this,SIGNAL(clicked()),SLOT(__change_color()));
}

Facelet::Facelet(int color,QWidget* parent) :
    QPushButton(parent),_ColorIndex(color)
{
    this->resize(75,75);
    this->setStyleSheet(colors[_ColorIndex]);
    connect(this,SLOT(__change_color()));
}

void Facelet::reset() {
    this->setStyleSheet("background-color: gray");
}

//private

void Facelet::__change_color() {
    _ColorIndex = (_ColorIndex >= 5 ) ? 0 : (_ColorIndex + 1);
    this->setStyleSheet(colors[_ColorIndex]);
}

这里是我的 main.cpp

#include <QApplication>
#include <QMainWindow>
#include "Facelet.h"

int main(int argc,char *argv[])
{
    QApplication a(argc,argv);
    QMainWindow w;
    Facelet f;
    w.setCentralWidget(&f);
    w.show();
    return a.exec();
}

enter image description here

看到了吗?屏幕褪色,我想要一个统一的强烈色彩。我的代码有什么问题?

解决方法

为了纠正我通过重新实现 odpaintEvent 方法找到了两个解决方案。 先

void Facelet::paintEvent(QPaintEvent*) {
    QPainter p(this);
    p.setOpacity(1.0);
}

第一个很简单,阅读一些主题后我发现 QWidget 要使 setStyleSheet(QString) 方法正常工作需要 paintEvent(QPaintEvent*) 方法中的以下行,如官方文档所述

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