Search code examples
qtstylesqtabbarqicon

QT Custom QStyle for QTabBar and QIcon


I have customize a Qtabbar's QMdiarea to get horizontal tab instead of vertical tab like this : http://www.qtcentre.org/wiki/index.php?title=Customizing_QTabWidget%27s_QTabBar

But i want to insert icon in my QTabBar. If I apply my custom style to my QTabBar my icons doesn't appear. If I don't apply, my icon appear.

here my custom style :

class CustomTabStyle : public QPlastiqueStyle
{
   Q_OBJECT
public:
QSize sizeFromContents(ContentsType type, const QStyleOption *option,const QSize &size, const QWidget *widget) const
{
    QSize s = QPlastiqueStyle::sizeFromContents(type, option, size, widget);
    if (type == QStyle::CT_TabBarTab)
        s.transpose();
    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))
        {
            QStyleOptionTab opt(*tab);
            opt.shape = QTabBar::RoundedNorth;
            QPlastiqueStyle::drawControl(element, &opt, painter, widget);
            return;
        }
    }
    QPlastiqueStyle::drawControl(element, option, painter, widget);
}

};

and i apply my style like this :

    mMdiAreaDock=aMdiArea;
m_pMdiAreaTabBar = NULL;
QObjectList listChildren = mMdiAreaDock->children();
for (QObjectList::Iterator i = listChildren.begin(); i != listChildren.end(); ++i)
{
    if (QString((*i)->metaObject()->className()) == "QTabBar")
    {
        m_pMdiAreaTabBar = dynamic_cast<QTabBar*>(*i);
        break;
    }
}
m_pMdiAreaTabBar->setStyle(new CustomTabStyle());
return 0;

where mMdiAreaDock is an QMdiArea and m_pMdiAreaTabBar is a QTabBar


Solution

  • Look at this code:

    const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option));
    QStyleOptionTab opt(*tab);
    

    option is an instance of QStyleOptionTabV2.

    When you create a new object QStyleOptionTab opt with copy constructor, you lose some important data which extended QStyleOptionTabV2 contains including information about an icon.

    Use this code instead:

    if (const QStyleOptionTabV2 *tab = qstyleoption_cast<const QStyleOptionTabV2 *>(option))
    {
        QStyleOptionTabV2 opt(*tab);
        opt.shape = QTabBar::RoundedNorth;
        QPlastiqueStyle::drawControl(element, &opt, painter, widget);
        return;
    }
    

    ps. I used this code to assign an icon for a specific tab:

     m_pMdiAreaTabBar->setTabIcon(0, icon);