QT中怎么使用QPalette设置按钮控件背景色

这里写自定义目录标题

 ui->pushButton->setAutoFillBackground(true);
    //获得当前选择的颜色值
    QStringList colorList = QColor:: colorNames();
    QColor color= QColor(colorList[ui->comboBox_3->currentIndex()]);
    QPalette p = ui->frame_2->palette();
    p.setColor (QPalette::Button,color);
    //把修改后的调色板信息应用到 frame_2 窗体中,更新显示
     ui->frame_2->setPalette(p);
    // ui->frame_2->update();

关于以上代码:并没有实现设置按钮控件的背景色
但是参照QT的帮助文档:
QT中怎么使用QPalette设置按钮控件背景色_第1张图片
照上面这么讲确实应该可以改变按钮背景色
但是程序运行之后却只能改变按钮边框的颜色
网上一搜 发现基本上都是说用样式表
但是我这个程序是要实现自己选择颜色来改变按钮的背景色 样式表当然就无济于事了 经过一番查找终于寻得解决办法:把按钮扁平化
flat : bool 存按钮是否扁平化。 默认为false。 除非按下或选中扁平按钮,否则不会绘制背景。

 ui->pushButton->setAutoFillBackground(true);
   ui->pushButton->setFlat(true);// flat : bool 存按钮是否扁平化。 默认为false。 除非按下或选中扁平按钮,否则不会绘制背景。
    //获得当前选择的颜色值
    QStringList colorList = QColor:: colorNames();
    QColor color= QColor(colorList[ui->comboBox_3->currentIndex()]);
    QPalette p = ui->frame_2->palette();
    p.setColor (QPalette::Button,color);
    //把修改后的调色板信息应用到 frame_2 窗体中,更新显示
     ui->frame_2->setPalette(p);
    // ui->frame_2->update();

你可能感兴趣的:(QT,qt,ui,开发语言)