正常设置QTabWidget->setTabPosition(QTabWidget::West);设置完竖向之后会发现QTabBar仍然是竖向的
所以我们需要重绘一下Qtabbar 下面是重绘代码
/******************customTabStyle.h**************************/
1 #ifndef CUSTOMTABSTYLE_H
2 #define CUSTOMTABSTYLE_H
3 #include <QPainter>
4 #include <QProxyStyle>
5 #include <QStyleOptionTab>
6 #include <QRect>
7 #include <QSize>
8 class CustomTabStyle : public QProxyStyle
9 {
10 public:
11 QSize sizeFromContents(ContentsType type, const QStyleOption *option,
12 const QSize &size, const QWidget *widget) const
13 {
14 QSize s = QProxyStyle::sizeFromContents(type, option, size, widget);
15 if (type == QStyle::CT_TabBarTab) {
16 s.transpose();
17 s.rwidth() = 150; // 设置每个tabBar中item的大小
18 s.rheight() = 50;
19 }
20 return s;
21 }
22 void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
23 {
24 if (element == CE_TabBarTabLabel) {
25 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
26 QRect allRect = tab->rect;
27 allRect.setWidth(allRect.width() - 5);
28 allRect.setHeight(allRect.height() - 2);
29 //选中状态
30 if (tab->state & QStyle::State_Selected) {
31 //save用以保护坐标,restore用来退出状态
32 painter->save();
33 painter->setBrush(QBrush(0x004ea1));
34 //矩形
35 //painter->drawRect(allRect.adjusted(0, 0, 0, 0));
36 //带有弧线矩形
37 painter->drawRoundedRect(tab->rect, 8, 8);
38 painter->restore();
39 }
40 //hover状态
41 else if(tab->state & QStyle::State_MouseOver){
42 painter->save();
43 painter->setBrush(QBrush(0x004ea1));
44 painter->drawRoundedRect(allRect, 8, 8);
45 painter->restore();
46 }
47 else{
48 painter->save();
49 painter->setBrush(QBrush(0x78aadc));
50 painter->drawRoundedRect(allRect, 8, 8);
51 painter->restore();
52 }
53 QTextOption option;
54 option.setAlignment(Qt::AlignCenter);
55 painter->setFont(QFont("楷体", 18, QFont::Bold));
56 painter->setPen(0xffffff);
57 painter->drawText(allRect, tab->text, option);
58 return;
59 }
60 }
61 if (element == CE_TabBarTab) {
62 QProxyStyle::drawControl(element, option, painter, widget);
63 }
64 }
65 };
endif // CUSTOMTABSTYLE_H
/****************************引用方法*****************************/
1 QTabWidget* tab = new QTabWidget();
2 QPushButton* closeButton = new QPushButton;
3 closeButton->setObjectName("closeButton");
4 QPushButton* button = new QPushButton("button");
5 tab->addTab(closeButton, "关闭");
6 tab->addTab(button, "按钮");
7 tab->setTabPosition(QTabWidget::West);//QTabWidget竖向
8 tab->tabBar()->setStyle(new CustomTabStyle);//注意,设置上述代码风格 就可以实现QTabBar横向
9 setCentralWidget(tab);