如何解决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();
}
看到了吗?屏幕褪色,我想要一个统一的强烈色彩。我的代码有什么问题?
解决方法
为了纠正我通过重新实现 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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。