样式部分:
class CustomTabStyle : public QProxyStyle
{
public:
QSize sizeFromContents(ContentsType type, const QStyleOption *option,
const QSize &size, const QWidget *widget) const
{
QSize s = QProxyStyle::sizeFromContents(type, option, size, widget);
if (type == QStyle::CT_TabBarTab)
{
s.transpose();
s.rwidth() = 400; // 设置每个tabBar中item的大小
s.rheight() = 50;
}
return s;
}
void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
if (element == CE_TabBarTabLabel)
{
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option))
{
QRect allRect = tab->rect;
QPainterPath path;
path.moveTo(0, 100);
path.lineTo(70, 10);
path.cubicTo(80, 0, 90, 0, 100, 0);
path.lineTo(300, 0);
path.cubicTo(310, 0, 320, 0, 330, 10);
path.lineTo(400, 100);
path.closeSubpath();
QPen pen(Qt::SolidLine); // 创建一个实线画笔
pen.setColor(Qt::darkBlue); // 设置画笔颜色为蓝色
//选中状态
if (tab->state & QStyle::State_Selected)
{
painter->save();
painter->setBrush(QBrush(0x4ea1));
painter->drawPath(path);
painter->restore();
}
//hover状态
else if (tab->state & QStyle::State_MouseOver)
{
painter->save();
painter->setBrush(QBrush(0xffb400));
painter->drawPath(path);
painter->restore();
}
else
{
painter->save();
painter->setBrush(QBrush(0x78aadc));
painter->drawPath(path);
painter->restore();
}
QTextOption option;
option.setAlignment(Qt::AlignCenter);
painter->setFont(QFont("楷体", 18, QFont::Bold));
painter->setPen(0xffffff);
painter->drawText(allRect, tab->text, option);
return;
}
}
if (element == CE_TabBarTab)
{
QProxyStyle::drawControl(element, option, painter, widget);
}
}
};
调用部分:
QTabWidget *tab = new QTabWidget();
QPushButton *test1 = new QPushButton("test1");
QPushButton *test2 = new QPushButton("test2");
tab->addTab(test1, "测试1");
tab->addTab(test2, "测试2");
tab->setTabPosition(QTabWidget::North); // QTabWidget竖向
tab->tabBar()->setStyle(new CustomTabStyle); // 设置上述
setCentralWidget(tab);
这是我使用QProxyStyle 自绘的梯型标签项, 但是有Bug, 只有一个显示了梯型, 别一个没有成功应用样式 ,希望大神看到我的博客, 跪求大神指导我一下.不胜感激!