When using menu with QToolButton
menu is shown right under the button. Is there a way to display menu in the left/right of the button?
Asked
Active
Viewed 2,201 times
3 Answers
4
I know this question was answered a while ago, but I wanted to add a new answer to this question since the accepted answer is no longer valid. It is actually quite easy to change the menu position on a QToolButton. You need to subclass QMenu and override the event function. When there is a show event, just change the position of the menu.
Here is a simple example using PySide:
from PySide import QtCore, QtGui
class MyMenu(QtGui.QMenu):
def event(self,event):
if event.type() == QtCore.QEvent.Show:
self.move(self.parent().mapToGlobal(QtCore.QPoint(0,0))-QtCore.QPoint(0,self.height()))
return super(MyMenu,self).event(event)
if __name__ == "__main__":
app = QtGui.QApplication([])
w = QtGui.QWidget()
w.setGeometry(100,100,500,500)
tb = QtGui.QToolButton(w)
tb.setText("HELLO")
tb.setGeometry(70,70,40,30)
m = MyMenu("Menu",tb)
m.addAction("Exit")
tb.setMenu(m)
w.show()
app.exec_()

spikeynick
- 499
- 6
- 12
-
Works like a charm, thanks! BTW, you can also use an eventFilter if you don't want (or can't) inherit `QMenu` – cbuchart Jun 10 '19 at 16:16
3
The position is hard-coded in the function void QToolButtonPrivate::popupTimerDone()
in [Qt install directory]/src/gui/widgets/qtoolbutton.cpp. It seems pretty hard to override that, unless you implement your own popup menu from scratch.

Johan Råde
- 20,480
- 21
- 73
- 110
-1
Just move the menu when the menu showing. This is the trick.
QMenu* menu = new Menu();
somePushButton->setMenu(menu);
menu->installEventFilter(this);
bool myWidget::eventFilter(QObject * obj, QEvent *event)
{
if (event->type() == QEvent::Show && obj == somePushButton->menu())
{
QPoint pos = calculateposition
somePushButton->menu()->move(pos);
return true;
}
return false;
}
Please check this thread.

W.Perrin
- 4,217
- 32
- 31