[Qt-interest] Setting the background color of a tab
Stefan Löffler
st.loeffler at gmail.com
Thu Aug 4 11:41:10 CEST 2011
Hi,
On 2011-08-04 10:23, Jonas Gehring wrote:
> Hi Jake,
>
> Here's a short example for a custom QTabBar implementation. You
> need to subclass QTabWidget in order to use it.
>
> class ColorTabBar : public QTabBar
> {
> public:
> ColorTabBar(QWidget *parent = 0) : QTabBar(parent) { }
>
> void setTabColor(int index, const QColor &color) {
> m_colors[index] = color;
> }
>
> protected:
> void paintEvent(QPaintEvent *event) {
> QStylePainter p(this);
> for (int i = 0; i < count(); i++) {
> QStyleOptionTabV3 option;
> QTabBar::initStyleOption(&option, i);
>
> // Apply custom background color
> if (m_colors.contains(i)) {
> option.palette.setColor(backgroundRole(), m_colors[i]);
> }
>
> p.drawControl(QStyle::CE_TabBarTab, option);
> }
> }
>
> private:
> QMap<int, QColor> m_colors;
> };
>
> This should illustrate the basic idea. You should take a look at QTabBar's
> implementation for corner case handling, though:
> http://qt.gitorious.org/qt/qt/blobs/4.7/src/gui/widgets/qtabbar.cpp#line1526
Wouldn't it be better to simply override initStyleOption in your
subclass? Something like (not tested)
void initStyleOption(QStyleOptionTab *option, int tabIndex) const
{
QTabBar::initStyleOption(option, tabIndex);
if (option && m_colors.contains(i)) {
option->palette.setColor(backgroundRole(), m_colors[i]);
}
}
HTH
Stefan
More information about the Qt-interest-old
mailing list