如何为自定义形状的Qbutton设置样式表

how to set style sheet for custom shaped Qpushbutton

本文关键字:Qbutton 设置 样式 自定义      更新时间:2023-10-16

我继承了Qbutton使其成为圆形,如果我在这个类的paintevent中设置背景,它可以很好地工作,但我想为这个类的每个瞬间设置不同的图像,所以我尝试通过seticon和setstylesheet设置它,但它不起作用。原因可能是什么。请帮帮我。提前谢谢。

这是我的密码。

CirclularButton::CirclularButton(QWidget *parent):QPushButton(parent)
{
}
void CirclularButton::paintEvent(QPaintEvent *e)
{
    QPainter p(this);
    p.setRenderHints(QPainter::Antialiasing);
    p.drawEllipse(0, 0, 50, 50);
}
and in another class where I am using it,
 CirclularButton *cir = new CirclularButton(this);
    cir->setGeometry(50,50,50,50);
    cir->setStyleSheet("border:1px solid red");

正如这里的文档中所解释的,您需要将其添加到您的绘画事件中:

 void paintEvent(QPaintEvent *e)
 {
     QStyleOption opt;
     opt.init(this);
     QPainter p(this);
     style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
     //your other code here
 }