基本函数
void QWidget::setStyle(QStyle *style)
使用办法:
1、实现自定义接口类
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() = 85; // 设置每个tabBar中item的大小
s.rheight() = 52; //45;
//option.setAlignment(Qt::AlignRight|Qt::AlignHCenter);
}
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;
allRect.setWidth(allRect.width()); // - 5
allRect.setHeight(allRect.height()); //- 2
painter->setFont(QFont("黑体", 10)); //QFont::Bold
painter->setPen(Qt::transparent);
QTextOption option;
option.setAlignment(Qt::AlignCenter); // Qt::AlignRight|Qt::AlignVCenter
QRect linRect;
linRect= QRect(tab->rect.left()+78,tab->rect.top(),1,tab->rect.height());
QBrush redbrush(QColor(Qt::lightGray),Qt::SolidPattern); //lightGray
painter->setBrush(redbrush);
painter->drawRect(linRect);
QRect linRect1= QRect(78,0,1,14);
QRect linRect2= QRect(78,widget->height() -14,1,12);
QBrush redbrush1(QColor(QColor(0xF0F0F0)),Qt::SolidPattern); //lightGray
painter->setBrush(redbrush1);
painter->drawRect(linRect1);
painter->drawRect(linRect2);
//选中状态
if (tab->state & QStyle::State_Selected)
{
//save用以保护坐标,restore用来退出状态
painter->save();
painter->setBrush(QBrush(Qt::transparent));
//矩形
painter->drawRect(allRect.adjusted(0, 0, 0, 0));
//带有弧线矩形
//painter->drawRoundedRect(tab->rect, 8, 8);
painter->restore();
painter->setBrush(QBrush(QColor(0xFF7E3D)));
painter->drawEllipse(tab->rect.left()+74,tab->rect.top()+22,8,8);
painter->setPen(0xFF7E3D);
}
//hover状态
else if(tab->state & QStyle::State_MouseOver){
painter->save();
painter->setBrush(QBrush(Qt::transparent));
//painter->drawRoundedRect(allRect, 8, 8); 0x004ea1
painter->drawRect(allRect.adjusted(0, 0, 0, 0));
painter->restore();
painter->setBrush(QBrush(QColor(0xFF7E3D)));
painter->drawEllipse(tab->rect.left()+76,tab->rect.top()+24,4,4);
painter->setPen(0xFF7E3D);
}
else{
painter->save();
painter->setBrush(QBrush(Qt::transparent));
//painter->drawRoundedRect(allRect, 8, 8);//0x78aadc
painter->drawRect(allRect.adjusted(0, 0, 0, 0));
painter->restore();
painter->setPen(0x000002);
}
painter->setFont(QFont("黑体", 10)); //, QFont::Bold
painter->drawText(allRect, tab->text, option);
return;
}
}
if (element == CE_TabBarTab) {
QProxyStyle::drawControl(element, option, painter, widget);
}
}
};
2、把这个类设置到需要自定义的控件上
m_tabWidget->tabBar()->setStyle(new CustomTabStyle);//注意,设置上述代码风格 就可以实现QTabBar横向