c++qtqtstylesheetsqtabwidget

QTabwidget's tab text alignment not working


i am trying to show the opened tab text in left .i wrote that in stylesheet.but it is not working.

here is the stylesheet i used

QTabWidget QTabBar{
    background-color: #373738;
    height: 30px;
}

QTabWidget QTabBar::tab{
    text-align: left;
    background-color: #136ba2;
    border-style: 1px rgb(67, 67, 67);
    height: 30px;
    width: 130px;
    color: #136ba2;
    padding: 0px 5px 0px 5px;
}

QTabWidget QTabBar::tab:selected{
    background-color: #5A5B5C;
    font-weight: bold;
    color: #ffffff;
}
QTabWidget QTabBar::tab:!selected{
    background-color:#353536;
    color:  #B4B4B4;
}
QTabWidget QTabBar::tab:hover{
    background-color:  #5A5B5C;
    color:  #ffffff;
}

here is an image


Solution

  • This can be accomplished using the tab button widget to show the tab text.

    Have a label, with left aligned text:

    QLabel * button = new QLabel("text");
    button->setAlignment(Qt::AlignLeft);
    

    Set the tab text to empty string if necessary:

    ui->tabWidget->tabBar()->setTabText(index, "");
    

    Set the label as the tab button widget:

    ui->tabWidget->tabBar()->setTabButton(index, QTabBar::LeftSide, button);
    

    You can still style the label, adding a QLabel entry in the tab widget stylesheet:

    QLabel{ color: white; }
    

    Only problem here: no way to style the label text depending on selection (i.e. making the selected tab text bold) using CSS. But still feasible catching the tab widget currentChanged signal:

    void Form::on_tabWidget_currentChanged(int index)
    {
        for(int i=0; i<ui->tabWidget->tabBar()->count(); i++)
        {
            QWidget * button = ui->tabWidget->tabBar()->tabButton(i, QTabBar::LeftSide);
            if(button != nullptr)
            {
                QFont font = button->font();
                font.setBold(i == index);
                button->setFont(font);
            }
        }
    }