Evgenii Legotckoi
Aug. 31, 2015, 8:39 p.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.

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QSqlTableModel>
  6.  
  7. #include <database.h>
  8. #include <dialogadddevice.h>
  9.  
  10. namespace Ui {
  11. class MainWindow;
  12. }
  13.  
  14. class MainWindow : public QMainWindow
  15. {
  16. Q_OBJECT
  17.  
  18. public:
  19. explicit MainWindow(QWidget *parent = 0);
  20. ~MainWindow();
  21.  
  22. private slots:
  23. void on_addDeviceButton_clicked();
  24. void slotUpdateModels();
  25. /* To the slot for editing entries are added to remove the recording SLOT.
  26.   * Also, add a slot for processing context menu
  27. * */
  28. void slotEditRecord();
  29. void slotRemoveRecord();
  30. void slotCustomMenuRequested(QPoint pos);
  31.  
  32. private:
  33. Ui::MainWindow *ui;
  34. DataBase *db;
  35. QSqlTableModel *modelDevice;
  36.  
  37. private:
  38. void setupModel(const QString &tableName, const QStringList &headers);
  39. void createUI();
  40. };
  41.  
  42. #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.

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. MainWindow::MainWindow(QWidget *parent) :
  5. QMainWindow(parent),
  6. ui(new Ui::MainWindow)
  7. {
  8. /* Program code without any changes in lesson on QDataWidgetMapper */
  9. }
  10.  
  11. MainWindow::~MainWindow()
  12. {
  13. delete ui;
  14. }
  15.  
  16. void MainWindow::setupModel(const QString &tableName, const QStringList &headers)
  17. {
  18. /* Program code without any changes in lesson on QDataWidgetMapper */
  19. }
  20.  
  21. void MainWindow::createUI()
  22. {
  23. ui->deviceTableView->setModel(modelDevice);
  24. ui->deviceTableView->setColumnHidden(0, true);
  25. ui->deviceTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  26. ui->deviceTableView->setSelectionMode(QAbstractItemView::SingleSelection);
  27. ui->deviceTableView->resizeColumnsToContents();
  28. ui->deviceTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
  29. ui->deviceTableView->horizontalHeader()->setStretchLastSection(true);
  30.  
  31. // Set the Context Menu
  32. ui->deviceTableView->setContextMenuPolicy(Qt::CustomContextMenu);
  33.  
  34. connect(ui->deviceTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(slotEditRecord()));
  35. // Connect SLOT to context menu
  36. connect(ui->deviceTableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotCustomMenuRequested(QPoint)));
  37. }
  38.  
  39. void MainWindow::on_addDeviceButton_clicked()
  40. {
  41. /* Program code without any changes in lesson on QDataWidgetMapper */
  42. }
  43.  
  44. void MainWindow::slotCustomMenuRequested(QPoint pos)
  45. {
  46. /* Create an object context menu */
  47. QMenu * menu = new QMenu(this);
  48. /* Create actions to the context menu */
  49. QAction * editDevice = new QAction(trUtf8("Редактировать"), this);
  50. QAction * deleteDevice = new QAction(trUtf8("Удалить"), this);
  51. /* Connect slot handlers for Action pop-up menu */
  52. connect(editDevice, SIGNAL(triggered()), this, SLOT(slotEditRecord())); // Call Handler dialog editing
  53. connect(deleteDevice, SIGNAL(triggered()), this, SLOT(slotRemoveRecord())); // Handler delete records
  54. /* Set the actions to the menu */
  55. menu->addAction(editDevice);
  56. menu->addAction(deleteDevice);
  57. /* Call the context menu */
  58. menu->popup(ui->deviceTableView->viewport()->mapToGlobal(pos));
  59. }
  60.  
  61. /* Slot to remove records from a table
  62. * */
  63. void MainWindow::slotRemoveRecord()
  64. {
  65. /* We find out which of the lines has been selected
  66. * */
  67. int row = ui->deviceTableView->selectionModel()->currentIndex().row();
  68. /* Check that the line was chosen
  69. * */
  70. if(row >= 0){
  71. /* We are asking the question, whether really delete the record.
  72.   * If yes - delete entry
  73. * */
  74. if (QMessageBox::warning(this,
  75. trUtf8("Удаление записи"),
  76. trUtf8("Вы уверены, что хотите удалить эту запись?"),
  77. QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
  78. {
  79. /* If the answer is do a rollback of actions and close the dialog box without deleting the entry
  80. * */
  81. QSqlDatabase::database().rollback();
  82. return;
  83. } else {
  84. /* Otherwise, we make the removal of records.
  85. * Upon successful remotely update the table.
  86. * */
  87. if(!modelDevice->removeRow(row)){
  88. QMessageBox::warning(this,trUtf8("Уведомление"),
  89. trUtf8("Не удалось удалить запись\n"
  90. "Возможно она используется другими таблицами\n"
  91. "Проверьте все зависимости и повторите попытку"));
  92. }
  93. modelDevice->select();
  94. ui->deviceTableView->setCurrentIndex(modelDevice->index(-1, -1));
  95. }
  96. }
  97. }
  98.  
  99. /* Slot update data representation model
  100. * */
  101. void MainWindow::slotUpdateModels()
  102. {
  103. modelDevice->select();
  104. ui->deviceTableView->resizeColumnsToContents();
  105. }
  106.  
  107. /* Method for activating dialogue adding entries
  108.  * to the edit mode with the transmission of the selected row index
  109. * */
  110. void MainWindow::slotEditRecord()
  111. {
  112. /* Also, create a dialogue and connect it
  113.   * to signal the completion of the form slot refresh data representation model,
  114.   * but send as parameters recording line
  115. * */
  116. DialogAddDevice *addDeviceDialog = new DialogAddDevice(ui->deviceTableView->selectionModel()->currentIndex().row());
  117. connect(addDeviceDialog, SIGNAL(signalReady()), this, SLOT(slotUpdateModels()));
  118.  
  119. /* Runs dialog box
  120. * */
  121. addDeviceDialog->setWindowTitle(trUtf8("Редактировать Устройство"));
  122. addDeviceDialog->exec();
  123. }

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:

Do you like it? Share on social networks!

AC
  • March 4, 2020, 12:12 p.m.

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

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

... делаю

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

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

Evgenii Legotckoi
  • March 4, 2020, 2:06 p.m.
  • (edited)

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

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

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

AC
  • March 4, 2020, 7:30 p.m.

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

t
  • July 24, 2021, 7:39 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup