Search code examples
c++qtqt5qt-creator

qt create button when right click


I am new in qt I want to create a button when I right click

There is my code:

void MainWindow::right_clicked(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton)
        {
           QPushButton *item = new QPushButton();
           item->setIcon(QIcon(":/images/7928748-removebg-preview(1).ico"));
           item->setIconSize(QSize(32, 32));
           item->setGeometry(QRect(QPoint(event->x(), event->y()), QSize(32, 32)));
        }
}

But nothing appears


Solution

  • To capture any mouse event in a QWidget you must override the mousePressEvent method.

    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    protected:
        void mousePressEvent(QMouseEvent *event);
    };
    

    And in the mainwindow.cpp, implement it as follows:

    void MainWindow::mousePressEvent(QMouseEvent *event)
    {
        if(event->button() == Qt::RightButton) {
            // make mainwindow parent of this button by passing "this" pointer
            QPushButton *item = new QPushButton(QIcon(":/images/close-button-icon"), "", this);
    
            // set button position to the location of mouse click
            item->setGeometry(QRect(QPoint(event->x()-16, event->y()-16), QSize(32, 32)));
            item->show();
        }
    }
    

    If you don't save the pointer to QPushButton, then you will not be able to use it afterwards.

    Demo