QT button add menu


1、 Foreword

There are many ways to add a menu to a button in QT. You can left-click the pop-up menu or bind customcontextmenurequested(Const qpoint &) signal, right-click the customcontextmenu mode to pop up the menu;

When I use the left button to pop up the menu, I found that there will be drop-down triangles, which will affect the beauty, so I sorted out the methods to remove the drop-down triangles

2、 Remove the drop-down triangle after the button setting menu

1. Style removal (disadvantages: the drop-down triangle is hidden, but it still takes up space, and the text is not centered)

//Don’t show pictures


2. The slot function is used to manually display the menu mode

Idea: bind the slot function of the button, create a new qmenu in the slot function, set the position, and then display the menu

1) Create display menu during construction

QT button add menuQT button add menu

1 // call the constructor to create a menu
 2 void Widget::initMenu()
 3 {
 4     menu = new QMenu(this);
 5     menu->setWindowFlags(menu->windowFlags() | Qt::FramelessWindowHint);
 6     //menu->setAttribute(Qt::WA_TranslucentBackground);
 7     menu->setObjectName("senMenu");
 8     sendAction = menu->addAction("Selected line");
 9     ctrlAction = menu->addAction("Changed direction");
11     ui->pushButton->setCheckable(true);
12     ui->pushButton_2->setMenu(menu);
13     ui->pushButton_3->setMenu(menu);
14 // the shadow hides the triangle, but it still occupies the space on the right, and the font is not centered
15     ui->pushButton_3->setStyleSheet("QPushButton:menu-indicator{image:none;}");
16 }

Create menu when constructing

2) Calculated display position in slot function

QT button add menuQT button add menu

1 // button slot function
 2 void Widget::menuSlot()
 3 {
 4     QPoint pos = ui->pushButton->pos();
 6     pos.setX(pos.x() + 1);
 7     pos.setY(pos.y() + ui->pushButton->height() - 1);
 8 // calculate the menu position
 9     menu->exec(mapToGlobal(pos));
10 }

Display position calculation

3. Operation effect

From left to right, there are ideal effects, drop-down triangle effect and de triangle effect



Recommended Today

Crash tracking journey of IOS development (I)

Preface: Recently, I encountered a crash blood disaster caused by crash in daily development. In a release in early May, the crash rate of the app developed by the author was directly increased from one thousand to nearly two thousand. At that time, the project leader just needed to report the relevant situation of project […]