Segmentation fault on QMenu::exec



  • I'm trying to implement custom context menu for my widget that inherits QWebView.

    Here is widget's header (I'm omitting #include's):

    class BrowserView : public QWebView
    {
        Q_OBJECT
    public:
        BrowserView(QWidget *parent);
    
    public slots:
        void showContextMenu(const QPoint &);
    };
    

    And here is the source:

    BrowserView::BrowserView(QWidget *parent) : QWebView(parent)
    {
        setContextMenuPolicy(Qt::CustomContextMenu);
        connect(this, SIGNAL(customContextMenuRequested(QPoint)), this,
                SLOT(showContextMenu(const QPoint &)));
    }
    
    void BrowserView::showContextMenu(const QPoint &p)
    {
        QPoint globalPos = mapToGlobal(p);
    
        QMenu menu(this);
        menu.addAction("Menu item 1");
    
        QAction *selectedItem = menu.exec(globalPos);
    
        if (selectedItem) {
            qDebug() << "item was selected";
        } else {
            qDebug() << "item was not selected";
        }
    }
    

    Here is my layout:

    <ui version="4.0">
        <class>MainWindow</class>
        <widget class="QMainWindow" name="MainWindow">
            <property name="geometry">
                <rect>
                    <x>0</x>
                    <y>0</y>
                    <width>400</width>
                    <height>300</height>
                </rect>
            </property>
            <property name="windowTitle">
                <string>MainWindow</string>
            </property>
            <widget class="BrowserView">
                <property name="objectName">
                    <string>browserView</string>
                </property>
            </widget>
        </widget>
    
        <layoutDefault spacing="6" margin="11" />
        <pixmapfunction></pixmapfunction>
        <resources/>
        <connections/>
    </ui>
    

    When I click right mouse button, the application crashes with segmentation fault. I found out that segfault happens when menu.exec(globalPos) is called. I tried to rewrite it using DefaultContextMenu (onContextMenuEvent), but the result is the same.



  • I don't see any issue with the code. Did you try whether your code works with QMainWindow type ? i.e Use the above logic in QMainWIndow class and try context menu works.


  • Moderators

    @Daniil-Kolesnichenko Did you try to debug to see at which line exactly it is crashing?



  • @dheerendra oh, I found where was the problem, and it wasn't actually related to context menus. I use my own BrowserApp class that inherits QApplication but I found out that I inherited it the wrong way (constructor signature was wrong) and that caused some segfaults, including the one described in my question. So now I fixed that and everything works fine.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.