qt How to style a QToolBar > QToolButton overflow button?

4.2k views Asked by At

I would like to know how to, in a stylesheet, I can reach and style the "overflow button" that appears when a QToolBar with a bunch of QToolButtons is displayed because not all the buttons fit in the window.

Examples:

example 1

example 2

1

There are 1 answers

3
mhcuervo On BEST ANSWER

That "button" is a QToolBarExtension so you can select it in QSS using that class name.

Example:

QToolBarExtension {
    background-color: black;
}

This would be the result:

enter image description here

Another whay of selecting an object in QSS is by its object name. So QToolBarExtension#qt_toolbar_ext_button would work as well.

As it seems Qt does not provide a straightforward way of styling the extension button depending on its orientation I'll try to provide a workaround that will address your problem.

Inherit QToolBar to create a tool bar that updates the extension button name when orientation changes.

mytoolbar.h

#ifndef MYTOOLBAR_H
#define MYTOOLBAR_H

#include <QToolBar>

class MyToolBar : public QToolBar
{
    Q_OBJECT
public:
    explicit MyToolBar(QWidget *parent = 0);

signals:

private slots:
    void updateOrientation(Qt::Orientation orientation);

private:
    QObject *extButton;
};

#endif // MYTOOLBAR_H

mytoolbar.cpp

#include "mytoolbar.h"

MyToolBar::MyToolBar(QWidget *parent) :
    QToolBar(parent),
    extButton(0)
{
    // Obtain a pointer to the extension button
    QObjectList l = children();
    for (int i = 0; i < l.count(); i++) {
        if (l.at(i)->objectName() == "qt_toolbar_ext_button") {
            extButton = l.at(i);
            break;
        }
    }

    // Update extension nutton object name according to current orientation
    updateOrientation(orientation()); 

    // Connect orientationChanged signal to get the name updated every time orientation changes
    connect (this, SIGNAL(orientationChanged(Qt::Orientation )),
             this, SLOT(updateOrientation(Qt::Orientation)));
}

void MyToolBar::updateOrientation(Qt::Orientation orientation) {
    if (extButton == 0)
        return;
    if (orientation == Qt::Horizontal)
        extButton->setObjectName("qt_toolbar_ext_button_hor"); // Name of ext button when the toolbar is oriented horizontally.
    else
        extButton->setObjectName("qt_toolbar_ext_button_ver"); // Name of ext button when the toolbar is oriented vertically.
    setStyleSheet(styleSheet()); // Update stylesheet
}

Now you can style the button this way:

QToolBarExtension#qt_toolbar_ext_button_hor {
background-color: black;
}

QToolBarExtension#qt_toolbar_ext_button_ver {
background-color: red;
}

where qt_toolbar_ext_button_hor represents the button when the toolbar is oriented horizontally and qt_toolbar_ext_button_ver when vertically.