Solved Menù spawn point
-
How can I spawn this menù at the top of the button? Something like this
[menù]
[button]MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setAcceptDrops(true); //... add = new QPushButton(this); add->setIconSize(QSize(16,16)); add->setIcon(QIcon("add.png")); add->setGeometry(10,304,48,22); add->setText("Add"); connect(add, SIGNAL(released()), this, SLOT(addMenuShow())); //... } void MainWindow::addMenuShow() { QMenu* menu = new QMenu(add); addFile = new QAction(tr("Add file…"), this); addFile->setShortcut(QKeySequence(tr("L"))); menu->addAction(addFile); QPoint relative; relative.setX(10); relative.setY(275); QPoint pos = menu->mapFrom(add, relative); menu->move(pos); menu->exec(); }
Thank you in advance
-
Hi,
Do you mean add a menu to the QMenuBar from your QMainWindow ?
-
@SGaist No, spawn this menù at the top of his parent, the button called "add". The menù spawns on "add" click
-
That looks a bit strange and I haven't seen anything like that in any OS style guidelines. Why not use QPushButton::setMenu ?
-
@SGaist Let me explain: I have a button called "add", and I have a menu item called "addFile" When the button "add" is clicked, I would make sure that the menu item "addFile" appeared above it, anchored at the top: how can I do that?
-
Use the position of your button as reference and set the position of your menu based on that.
-
[SOLVED]
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setAcceptDrops(true); //... add = new QPushButton(this); add->setIconSize(QSize(16,16)); add->setIcon(QIcon("add.png")); add->setGeometry(10,304,48,22); add->setText("Add"); connect(add, SIGNAL(released()), this, SLOT(addMenuShow())); //... } void MainWindow::addMenuShow() { QMenu* menu = new QMenu(add); addFile = new QAction(tr("Add file…"), this); addFile->setShortcut(QKeySequence(tr("L"))); menu->addAction(addFile); QSize s = menu->sizeHint(); menu->popup(add->mapToGlobal(QPoint(0,0-s.height()))); }
-
Be aware that you are, sort of, leaking memory here. You are creating a new menu each time you click on the
add
button which will only be destroyed once the button is destroyed. -
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setAcceptDrops(true); //... add = new QPushButton(this); add->setIconSize(QSize(16,16)); add->setIcon(QIcon("add.png")); add->setGeometry(10,304,48,22); add->setText("Add"); bottomAdd = new QMenu(add); addFile = new QAction(tr("Add file…"), this); addFile->setShortcut(QKeySequence(tr("L"))); bottomAdd->addAction(addFile); connect(addFile, SIGNAL(triggered()), this, SLOT(openmediaOnClick())); //... } void MainWindow::addMenuShow() { QSize size = bottomAdd->sizeHint(); bottomAdd->popup(add->mapToGlobal(QPoint(0,0-size.height()))); }
-
Why not use
bottomAdd->height();
or its top left coordinate ?