Smi*_*ong 4 c++ qt qt5 qtstylesheets qtabwidget
这是原来的Tabwidget,没有设置标题背景色

我的客户要求我做这样的事情;为标题设置不同的背景颜色
All - Yellow
purchase - light blue
POS Sales - light green
Cash Sales - Pink
invoice - light purple
Run Code Online (Sandbox Code Playgroud)
我尝试过 SetStyleSheet 像:
QTabBar {
background-color : Yellow;
}
Run Code Online (Sandbox Code Playgroud)
但是所有选项卡颜色都改变了 有人知道如何设置每个 QTabBar 背景颜色吗?
这些属性无法通过 QSS 设置。要更改每个选项卡的样式,我们必须创建一个自定义QTabBar并重写其paintEvent方法,以便能够更改我们使用该类的每个选项卡的样式QStyleOptionTab,但是要更改QTabWidget选项卡栏,我们需要使用该setTabBar方法,但这是私有的,因此您需要创建自定义QTabWidget,如下所示:
tabwidget.h
#ifndef TABWIDGET_H
#define TABWIDGET_H
#include <QStyleOptionTab>
#include <QStylePainter>
#include <QTabWidget>
class TabBar: public QTabBar
{
public:
TabBar(const QHash<QString, QColor> &colors, QWidget *parent=0):QTabBar(parent){
mColors = colors;
}
protected:
void paintEvent(QPaintEvent */*event*/){
QStylePainter painter(this);
QStyleOptionTab opt;
for(int i = 0;i < count();i++)
{
initStyleOption(&opt,i);
if(mColors.contains(opt.text)){
opt.palette.setColor(QPalette::Button, mColors[opt.text]);
}
painter.drawControl(QStyle::CE_TabBarTabShape, opt);
painter.drawControl(QStyle::CE_TabBarTabLabel,opt);
}
}
private:
QHash<QString, QColor> mColors;
};
class TabWidget : public QTabWidget
{
public:
TabWidget(QWidget *parent=0):QTabWidget(parent){
// text - color
QHash <QString, QColor> dict;
dict["All"] = QColor("yellow");
dict["purchase"] = QColor("#87ceeb");
dict["POS Sales"] = QColor("#90EE90");
dict["Cash Sales"] = QColor("pink");
dict["invoice"] = QColor("#800080");
setTabBar(new TabBar(dict));
}
};
#endif // TABWIDGET_H
Run Code Online (Sandbox Code Playgroud)
要在 Qt Designer 中的 QTabWidget 中使用它,应该为此进行升级,我们右键单击 tabwidget 并选择菜单“Promoted Widgets”,在我的例子中,前面的代码是在文件 tabwidget.h 中创建的,因此这将是头文件和对于“Promoted Class Name”(升级类名称),我们使用 TabWidget,然后按“Add”(添加)和“Promote”(升级)按钮,获得如下图所示的内容:
最终结果如下图所示:
完整的示例可以在以下链接中找到
Python:
#ifndef TABWIDGET_H
#define TABWIDGET_H
#include <QStyleOptionTab>
#include <QStylePainter>
#include <QTabWidget>
class TabBar: public QTabBar
{
public:
TabBar(const QHash<QString, QColor> &colors, QWidget *parent=0):QTabBar(parent){
mColors = colors;
}
protected:
void paintEvent(QPaintEvent */*event*/){
QStylePainter painter(this);
QStyleOptionTab opt;
for(int i = 0;i < count();i++)
{
initStyleOption(&opt,i);
if(mColors.contains(opt.text)){
opt.palette.setColor(QPalette::Button, mColors[opt.text]);
}
painter.drawControl(QStyle::CE_TabBarTabShape, opt);
painter.drawControl(QStyle::CE_TabBarTabLabel,opt);
}
}
private:
QHash<QString, QColor> mColors;
};
class TabWidget : public QTabWidget
{
public:
TabWidget(QWidget *parent=0):QTabWidget(parent){
// text - color
QHash <QString, QColor> dict;
dict["All"] = QColor("yellow");
dict["purchase"] = QColor("#87ceeb");
dict["POS Sales"] = QColor("#90EE90");
dict["Cash Sales"] = QColor("pink");
dict["invoice"] = QColor("#800080");
setTabBar(new TabBar(dict));
}
};
#endif // TABWIDGET_H
Run Code Online (Sandbox Code Playgroud)