Evgenii Legotckoi
June 15, 2017, 12:58 p.m.

Qt/C++ - Tutorial 067. Using QMultiMap for a dictionary of synonyms

QMultiMap is a class inherited from QMap, which allows you to store multiple values for a single key. That is, the key can be repeated. This class can be used, for example, to represent a dictionary of synonyms.

Let's write a small program that will contain two tables:

  1. A table with keys
  2. A table with values that will be synonymous with words in the first table.

Initially, the table with the keys will be filled, while the table with the values will be empty. When you click on a row in the key table, the value table will be filled with synonyms of the word whose string was clicked.

Appearance of the application:


Project structure

  • QMultiMapExample.pro - Project profile, created by default and does not change
  • main.cpp - The file with the main function is created by default and does not change.
  • widget.ui - Form the application window, create a window, as in the picture above.
  • widget.h - Application window header file
  • widget.cpp - The source file for the application window.

widget.h

To implement the task, we need the QMultiMap itself, which will contain the entire dictionary. The dictionary can be filled from a file, or manually through a special input that you can provide, or in any other ways. And in this case, we fill the dictionary of synonyms when the application is launched. There will be three keys and each will be three synonyms.

We will also need data models to display the QMultiMap keys and values in the tables. To do this, we use QStandardItemModel .

And we'll write a slot for processing the click on the rows in the key table. In this slot, we will fill out the value table.

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5. #include <QMultiMap>
  6. #include <QStandardItemModel>
  7. #include <QModelIndex>
  8.  
  9. namespace Ui {
  10. class Widget;
  11. }
  12.  
  13. class Widget : public QWidget
  14. {
  15. Q_OBJECT
  16.  
  17. public:
  18. explicit Widget(QWidget *parent = 0);
  19. ~Widget();
  20.  
  21. public slots:
  22. void wordsTableViewClicked(const QModelIndex &index);
  23.  
  24. private:
  25. Ui::Widget *ui;
  26. QMultiMap<QString, QString> m_synonymousMap;
  27. QStandardItemModel m_keysModel;
  28. QStandardItemModel m_valuesModel;
  29. };
  30.  
  31. #endif // WIDGET_H

widget.cpp

The data model will be enough to install into the tables once, after which we will clean them if necessary.

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. Widget::Widget(QWidget *parent) :
  5. QWidget(parent),
  6. ui(new Ui::Widget)
  7. {
  8. ui->setupUi(this);
  9.  
  10.   // We fill the dictionary of synonyms
  11. m_synonymousMap.insert("daemon", "demon");
  12. m_synonymousMap.insert("daemon", "devil");
  13. m_synonymousMap.insert("daemon", "demonic");
  14.  
  15. m_synonymousMap.insert("chief", "head");
  16. m_synonymousMap.insert("chief", "senior");
  17. m_synonymousMap.insert("chief", "superior");
  18.  
  19. m_synonymousMap.insert("road", "roadway");
  20. m_synonymousMap.insert("road", "high road");
  21. m_synonymousMap.insert("road", "highway");
  22.  
  23.   // We take away all the keys and fill the model of these keys
  24. // QMultiMap :: uniqueKey () method returns a list of keys without duplicates
  25. // the usual method keys () will return keys in this dictionary three times,
  26.   // whereas this method will return each key once
  27. for (auto key : m_synonymousMap.uniqueKeys())
  28. {
  29. m_keysModel.appendRow(new QStandardItem(key));
  30. }
  31.  
  32.   // Set data models in tables
  33. ui->wordsTableView->setModel(&m_keysModel);
  34. ui->synonymsTableView->setModel(&m_valuesModel);
  35.  
  36.   // Connect a click signal to the line to process this click in the slot
  37. connect(ui->wordsTableView, &QTableView::clicked, this, &Widget::wordsTableViewClicked);
  38. }
  39.  
  40. Widget::~Widget()
  41. {
  42. delete ui;
  43. }
  44.  
  45. void Widget::wordsTableViewClicked(const QModelIndex &index)
  46. {
  47.   // We clear the data model so that there are no synonyms of the previous key
  48. m_valuesModel.clear();
  49.  
  50. // And fill the value model with synonyms
  51. // Since only one column is used in the row,
  52.   // we immediately take the key with the transmitted index from the model that is in the key table
  53. for (auto value : m_synonymousMap.values(ui->wordsTableView->model()->data(index).toString()))
  54. {
  55. m_valuesModel.appendRow(new QStandardItem(value));
  56. }
  57. }

Conclusion

As a result, we get an application that looks like the one shown in the figure at the beginning of the article.

Download application project

Do you like it? Share on social networks!

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