Evgenii Legotckoi
Evgenii LegotckoiAug. 31, 2015, 10:39 a.m.

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

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

mainwindow.h

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.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QSqlTableModel>

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

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

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);

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

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

#endif // MAINWINDOW_H

mainwindow.cpp

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) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    /* Program code without any changes in lesson on QDataWidgetMapper */
}

MainWindow::~MainWindow()
{
    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->setModel(modelDevice);
    ui->deviceTableView->setColumnHidden(0, true);
    ui->deviceTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->deviceTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->deviceTableView->resizeColumnsToContents();
    ui->deviceTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->deviceTableView->horizontalHeader()->setStretchLastSection(true);

    // Set the Context Menu
    ui->deviceTableView->setContextMenuPolicy(Qt::CustomContextMenu);

    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 */
    menu->addAction(editDevice);
    menu->addAction(deleteDevice);
    /* Call the context menu */
    menu->popup(ui->deviceTableView->viewport()->mapToGlobal(pos));
}

/* 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
             * */
            QSqlDatabase::database().rollback();
            return;
        } else {
            /* Otherwise, we make the removal of records. 
             * Upon successful remotely update the table.
             * */
            if(!modelDevice->removeRow(row)){
                QMessageBox::warning(this,trUtf8("Уведомление"),
                                     trUtf8("Не удалось удалить запись\n"
                                            "Возможно она используется другими таблицами\n"
                                            "Проверьте все зависимости и повторите попытку"));
            }
            modelDevice->select();
            ui->deviceTableView->setCurrentIndex(modelDevice->index(-1, -1));
        }
    }
}

/* Slot update data representation model
 * */
void MainWindow::slotUpdateModels()
{
    modelDevice->select();
    ui->deviceTableView->resizeColumnsToContents();
}

/* 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("Редактировать Устройство"));
    addDeviceDialog->exec();
}

Result

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.

Do you like it? Share on social networks!

AC
  • March 4, 2020, 1:12 a.m.

Доброго дня.
У меня вопрос по поводу нового синтаксиса.
Никак не могу разобраться с подключением СЛОТ-а

connect(ui->deviceTableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotCustomMenuRequested(QPoint)));

... делаю

connect(ui->deviceTableView, QOverload<const QPoint &>::of(&QWidget::customContextMenuRequested),
        this, QOverload<const QPoint &>::of(&MainWindow::slotCustomMenuRequested));

... но с ошибкой.

Evgenii Legotckoi
  • March 4, 2020, 3:06 a.m.
  • (edited)

Добрый день. Если у вас нет перегрузок сигналов или слотов, то QOverload Вам не нужен

connect(ui->deviceTableView, &QWidget::customContextMenuRequested, this, &MainWindow::slotCustomMenuRequested);

Ошибка при компиляции? Или QtCreator подсвечивает что-то красным без компиляции? И почему не привели текст ошибки? Экстрасены в отпуске.

AC
  • March 4, 2020, 8:30 a.m.

Спасибо за ответ. Да перегрузок сигналов нет.

t
  • July 24, 2021, 9:39 a.m.

Добрый день,
в строке 49 файла mainwindow.cpp создаётся меню и оно будет создаваться каждый раз при его вызове. Т.е. каждый раз будет выделяться память под QMenu. Это же утечка памяти или Qt как то сам освобождает память при выходе их слота slotCustomMenuRequested?

Comments

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

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

  • Result:33points,
  • Rating points-10
г
  • ги
  • April 23, 2024, 8:51 p.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 2:19 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
Last comments
k
kmssrFeb. 8, 2024, 11:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 3:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 1:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 2:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 10:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 12:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 11:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 7:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 9:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks