QPushButton with menu - drop from right side

1.4k views Asked by At

I have a long QPushButton (well, a subclass of one) with a menu attached. The drop-down menu indicator is on the right side of the button, but when pressed the menu drops down from the bottom-left corner. This seems to me like it will be clunky and unintuitive for my users.

Left-side drop down menu

I've looked through the QPushButton source code, and tried:

this->setLayoutDirection(Qt::RightToLeft);

which did move the menu to the right side, but it broke the button as it also moved the indicator to the left side and made the menus backwards.

enter image description here

Is there another way to make the menu drop from the right side?

1

There are 1 answers

0
Nicolas Holthaus On BEST ANSWER

It can be done by installing an event filter on the menu used for the QPushButton which moves it when shown.

class rightSideMenuFilter : public QObject
{
public:

    bool eventFilter(QObject * obj, QEvent *event)
    {
        QPushButton* parentButton = dynamic_cast<QPushButton*>(obj->parent());
        if (!parentButton)
            return false;

        QMenu* menu = dynamic_cast<QMenu*>(obj);
        if (!menu)
            return false;

        if (event->type() == QEvent::Show && obj == parentButton->menu())
        {
            QPoint pos = menu->pos();
            qDebug() << "pos" << pos;

            pos.setX(pos.x() + parentButton->width() - menu->width());
            parentButton->menu()->move(pos);
            return true;
        }
        return false;
    }
};