起因
QTabWidget默认的tabBar在最上端。
改进
但有时需要将tabBar放置在左侧,但是设置后效果如下…
最终
有时候需要如下效果,则需要自定义style:
附相应代码(具体边框可通过stylesheet进行设置)
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 #include <QPainter> 5 #include <QProxyStyle> 6 7 class CustomTabStyle : public QProxyStyle 8 { 9 public: 10 QSize sizeFromContents(ContentsType type, const QStyleOption *option, 11 const QSize &size, const QWidget *widget) const 12 { 13 QSize s = QProxyStyle::sizeFromContents(type, option, size, widget); 14 if (type == QStyle::CT_TabBarTab) { 15 s.transpose(); 16 s.rwidth() = 90; // 设置每个tabBar中item的大小 17 s.rheight() = 44; 18 } 19 return s; 20 } 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 28 if (tab->state & QStyle::State_Selected) { 29 painter->save(); 30 painter->setPen(0x89cfff); 31 painter->setBrush(QBrush(0x89cfff)); 32 painter->drawRect(allRect.adjusted(6, 6, -6, -6)); 33 painter->restore(); 34 } 35 QTextOption option; 36 option.setAlignment(Qt::AlignCenter); 37 if (tab->state & QStyle::State_Selected) { 38 painter->setPen(0xf8fcff); 39 } 40 else { 41 painter->setPen(0x5d5d5d); 42 } 43 44 painter->drawText(allRect, tab->text, option); 45 return; 46 } 47 } 48 49 if (element == CE_TabBarTab) { 50 QProxyStyle::drawControl(element, option, painter, widget); 51 } 52 } 53 }; 54 55 MainWindow::MainWindow(QWidget *parent) : 56 QMainWindow(parent), 57 ui(new Ui::MainWindow) 58 { 59 ui->setupUi(this); 60 ui->tabWidget->setTabPosition(QTabWidget::West); 61 ui->tabWidget->tabBar()->setStyle(new CustomTabStyle); 62 63 #if 0 64 ui->tabWidget->setStyleSheet("QTabWidget::pane{ \ 65 border-left: 1px solid #eeeeee;\ 66 }"); 67 #endif 68 } 69 70 MainWindow::~MainWindow() 71 { 72 delete ui; 73 }
标签:const,Qt,ui,tabBar,QTabWidget,MainWindow,painter,option From: https://www.cnblogs.com/ybqjymy/p/18022727