Qt/C++ - Lesson 013. QMenu – How to work with context menu in QTableView?

QMenu, QMenu example, QMenu Qt, Qt, контекстное меню, меню

To use the context menu in Qt is used QMenu class. When performing actions that should cause the menu handler is called, which creates the menu and binds handlers to act in this menu.

In this lesson, work with the shortcut menu will be shown in the example code from the tutorial on working with QDataWidgetMapper. In this lesson, the two files from the previous lesson will be modified, but the project will not work if you do not include it as in the previous lesson files that can not be edited.

Project structure for QMenu

Project structure remains the same as in the tutorial, which is based on the lesson. Changes in the code will be subjected to only two files:

  • mainwindow.h
  • mainwindow.cpp


Declare additional slots in the header file. This slot to display the shortcut menu, and delete the record. It is also necessary to rewrite the signature slot for editing entries, it will be used as a method of determining the selected entry.


#include <QMainWindow>
#include <QSqlTableModel>

#include <database.h>
#include <dialogadddevice.h>

namespace Ui {
class MainWindow;

class MainWindow : public QMainWindow

    explicit MainWindow(QWidget *parent = 0);

private slots:
    void on_addDeviceButton_clicked();
    void slotUpdateModels();
    /* To the slot for editing entries are added to remove the recording SLOT. 
     * Also, add a slot for processing context menu
     * */
    void slotEditRecord();
    void slotRemoveRecord();
    void slotCustomMenuRequested(QPoint pos);

    Ui::MainWindow              *ui;
    DataBase                    *db;
    QSqlTableModel              *modelDevice;

    void setupModel(const QString &tableName, const QStringList &headers);
    void createUI();

#endif // MAINWINDOW_H


This file will need to add the inclusion of the context menu for the tableView. And write a method to handle the shortcut menu and delete the entry from the table and, respectively, from the database. Along the way, we rewrite and method for editing entries.

As a result, you should have an application that is accessed by pressing right mouse button on the entry in the table, a context menu with two options: Edit and Delete . By pressing the Edit item will bring up the dialog box, as is the case with the action double-click from the previous lesson. And by pressing the Delete item is called MessageBox with a question to confirm the deletion, in the case of an affirmative result is produced delete records in the table.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)
    /* Program code without any changes in lesson on QDataWidgetMapper */

    delete ui;

void MainWindow::setupModel(const QString &tableName, const QStringList &headers)
    /* Program code without any changes in lesson on QDataWidgetMapper */

void MainWindow::createUI() 
    ui->deviceTableView->setColumnHidden(0, true);

    // Set the Context Menu

    connect(ui->deviceTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(slotEditRecord()));
    // Connect SLOT to context menu
    connect(ui->deviceTableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotCustomMenuRequested(QPoint)));

void MainWindow::on_addDeviceButton_clicked()
    /* Program code without any changes in lesson on QDataWidgetMapper */

void MainWindow::slotCustomMenuRequested(QPoint pos)
    /* Create an object context menu */
    QMenu * menu = new QMenu(this);
    /* Create actions to the context menu */
    QAction * editDevice = new QAction(trUtf8("Редактировать"), this);
    QAction * deleteDevice = new QAction(trUtf8("Удалить"), this);
    /* Connect slot handlers for Action pop-up menu */
    connect(editDevice, SIGNAL(triggered()), this, SLOT(slotEditRecord()));     // Call Handler dialog editing
    connect(deleteDevice, SIGNAL(triggered()), this, SLOT(slotRemoveRecord())); // Handler delete records
    /* Set the actions to the menu */
    /* Call the context menu */

/* Slot to remove records from a table
 * */
void MainWindow::slotRemoveRecord()
    /* We find out which of the lines has been selected
     * */
    int row = ui->deviceTableView->selectionModel()->currentIndex().row();
    /* Check that the line was chosen
     * */
    if(row >= 0){
        /* We are asking the question, whether really delete the record. 
         * If yes - delete entry
         * */
        if (QMessageBox::warning(this,
                                 trUtf8("Удаление записи"),
                                 trUtf8("Вы уверены, что хотите удалить эту запись?"),
                                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
            /* If the answer is do a rollback of actions and close the dialog box without deleting the entry
             * */
        } else {
            /* Otherwise, we make the removal of records. 
             * Upon successful remotely update the table.
             * */
                                     trUtf8("Не удалось удалить запись\n"
                                            "Возможно она используется другими таблицами\n"
                                            "Проверьте все зависимости и повторите попытку"));
            ui->deviceTableView->setCurrentIndex(modelDevice->index(-1, -1));

/* Slot update data representation model
 * */
void MainWindow::slotUpdateModels()

/* Method for activating dialogue adding entries 
 * to the edit mode with the transmission of the selected row index
 * */
void MainWindow::slotEditRecord()
    /* Also, create a dialogue and connect it 
     * to signal the completion of the form slot refresh data representation model, 
     * but send as parameters recording line
     * */
    DialogAddDevice *addDeviceDialog = new DialogAddDevice(ui->deviceTableView->selectionModel()->currentIndex().row());
    connect(addDeviceDialog, SIGNAL(signalReady()), this, SLOT(slotUpdateModels()));

    /* Runs dialog box
     * */
    addDeviceDialog->setWindowTitle(trUtf8("Редактировать Устройство"));


As a result, you have learned to call the context menu for the object QTableView and generally work with the class QMenu. Also, as a bonus issue was consecrated in parallel to remove records from a table, and a database with data representation model. Example QMenu behavior shown in the following video:

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

Feb. 17, 2020, 1:41 p.m.

C++ - Тест 003. Условия и циклы

  • Result:85points,
  • Rating points6
Feb. 17, 2020, 5:02 a.m.

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Feb. 17, 2020, 4:49 a.m.

C++ - Test 001. The first program and data types

  • Result:80points,
  • Rating points4
Last comments
Feb. 17, 2020, 2:22 a.m.
Evgenij Legotskoj

Добрый день. Это кастомный тег, помещается в файл, который находится в каталоге templatetags myapp/ templatetags/ myapp.py
Feb. 16, 2020, 12:36 p.m.

Добрый вечер! Монжно по подробней о теге get_companion? ссылка не работает.
Feb. 16, 2020, 8:35 a.m.
Evgenij Legotskoj

Добрый день. На GitHub исходники, можете посмотреть в официальном репозитории
Feb. 16, 2020, 8:29 a.m.

Здравстсвуйте Евгений, непонятно мне где эти исходники найти?
Now discuss on the forum
Feb. 18, 2020, 2:16 p.m.

Нет, стоит minLevel=1 А что это значит? Поменял на 0, но ничего не изменилось. Файл настроек выглядит так [listener]; host=…
Feb. 18, 2020, 6:19 a.m.

Привет , кто -нибудь подскажет как реализовать перетаскивание обьектов из листвью , и как это вообще делается ? Суть в том ,чтобы при объекта из листвью модели ,знать что за обьект. В…
Feb. 17, 2020, 2:11 p.m.

Добрый день. Сейчас инициализация моего приложение выглядит приблизительно так: sys_argv = sys.argvsys_argv += ['--style', 'material']app = QGuiApplication(sys_argv)app.setWindowIcon…
Feb. 16, 2020, 1:13 p.m.

Всем привет. есть те кто сталкивался с данной прогой? Нужна наводка просто как правильно из кучи инфы что содержит файл trace.dat и скармливается kernelshark вытащить причину долгого с…
Feb. 16, 2020, 10:35 a.m.
Igor' Poroshin

#include <QSqlError>#include <QSqlQuery>...if (!model->select()) { qDebug() << model->lastError().text(); qDebug() << model->query().lastQue…
© EVILEG 2015-2019
Recommend hosting TIMEWEB