2

I have some problem to locate my QMenu at runtime. menu->pos() is supposed to send his position back, but it sends QPoint(0,0). To find its real position I have to open that menu and hover a QAction.

Is there a way to initialize correct menu position without opening manually that menu?

The idea is showing the user where (s)he can find an option, and using exec or popup without correct position is not helping…

mainwindow.cpp (QMAKE_CXXFLAGS += -std=c++11)

#include "mainwindow.h"

#include <QMenu>
#include <QMenuBar>

#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QMenuBar * menuBar = new QMenuBar(this);
    QMenu    * menu    = new QMenu("File", this);

    menu->addAction("Action0");

    menuBar->addMenu(menu);

    qDebug() << menu->pos();

    connect(menu, &QMenu::hovered, this, [menu] {
        qDebug() << menu->pos();
    });

    setMenuBar(menuBar);
}

MainWindow::~MainWindow()
{

}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
 };

 #endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
  • *To find its real position* - What do you mean by **real position**? As the Qt docs state for [pos](http://doc.qt.io/qt-5/qwidget.html#pos-prop): *"This property holds the position of the widget within its parent widget."* So it's returning correctly, as its position is (0,0) relative to the MainWindow. – TheDarkKnight Aug 13 '15 at 08:32
  • 1
    As you can see on this image: https://lut.im/FRDsH1pu/xNdjjPg5 , the first `pos()` returns `QPoint(0,0)`, but after hovering the action in the menu `pos()` returns the menu position on the screen. I would like to get that position directly. – Astalaseven Aug 13 '15 at 17:26
  • Sorry, but I'm not quite sure what you're asking by *'get that position directly'*. It looks like you're getting the positions you're asking for. – TheDarkKnight Aug 14 '15 at 08:18

1 Answers1

0

Mmm... I know it is a bit late, but, two things:

  1. As the menu bar is created in the constructor, it doesn't have any position assigned yet, you'd have to query the position later (the moveEvent may be a good place and you have updated that position if the window moves).
  2. If such position is still relative to the parent window, you can use QMenuBar::mapToGlobal to map the local position to screen coordinates.
cbuchart
  • 10,847
  • 9
  • 53
  • 93