Qt RightClick on QListWidget Opens Contextmenu and Delete Item

后端 未结 1 1888
无人共我
无人共我 2021-02-12 22:20

I want to know how can I open a popup menu when I right click on the table items. In the popup menu some actions like add and delete should be given, which will create a new row

1条回答
  •  醉梦人生
    2021-02-12 23:02

    Firstly you need to create slot for opening context menu:

    void showContextMenu(const QPoint&);
    

    At constructor of your class, which used QListWidget, set context menu policy to custom and connect QListWidget::customContextMenuRequested(QPoint) signal and showContextMenu() slot like this:

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent)
    {
        setupUi(this);
    
        listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint)));
    }
    

    Then need to realize context menu opening:

    void MainWindow::showContextMenu(const QPoint &pos)
    {
        // Handle global position
        QPoint globalPos = listWidget->mapToGlobal(pos);
    
        // Create menu and insert some actions
        QMenu myMenu;
        myMenu.addAction("Insert", this, SLOT(addItem()));
        myMenu.addAction("Erase",  this, SLOT(eraseItem()));
    
        // Show context menu at handling position
        myMenu.exec(globalPos);
    }
    

    After this we need to realize slots for adding and removing QListWidget elements:

    void MainWindow::eraseItem()
    {
        // If multiple selection is on, we need to erase all selected items
        for (int i = 0; i < listWidget->selectedItems().size(); ++i) {
            // Get curent item on selected row
            QListWidgetItem *item = listWidget->takeItem(listWidget->currentRow());
            // And remove it
            delete item;
        }
    }
    

    As you can see we iterate all selected items (for set multiple selection mode use setSelectionMode() method) and delete it by ourself, because docs says that

    Items removed from a list widget will not be managed by Qt, and will need to be deleted manually.

    Adding some items is easier, my solution with static variable for different item caption looks like:

    void MainWindow::addItem()
     {
            static int i = 0;
            listWidget->addItem(QString::number(++i));
     }
    

    To simplify your code use Qt5 sytax for signals and slots. It eliminates the need to create intermediate slots.

    I hope it helps to you.

    0 讨论(0)
提交回复
热议问题