Advertisement
osipyonok

QComboboxStrangeBehavior

Dec 28th, 2019
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1. #include <QApplication>
  2. #include <QComboBox>
  3. #include <QPushButton>
  4. #include <QStringList>
  5. #include <QStringListModel>
  6. #include <QVBoxLayout>
  7.  
  8. #include <algorithm>
  9.  
  10. int main(int argc, char *argv[])
  11. {
  12.     QApplication a(argc, argv);
  13.  
  14.     QStringList strings = { "aaa", "bbb", "ccc", "ddd" };
  15.     //QStringListModel strings_model(strings);
  16.  
  17.     QStringList numbers = { "111", "222", "333", "444" };
  18.     //QStringListModel numbers_model(numbers);
  19.  
  20.     QWidget main_widget;
  21.     auto p_layout = new QVBoxLayout(&main_widget);
  22.  
  23.     auto p_combobox = new QComboBox(&main_widget);
  24.     Q_ASSERT(p_combobox->model());
  25.     //p_combobox->setModel(&strings_model);
  26.     p_layout->addWidget(p_combobox);
  27.  
  28.     auto p_reverse_items_button = new QPushButton("Reverse order of items", &main_widget);
  29.     p_layout->addWidget(p_reverse_items_button);
  30.     bool is_current_strings = true;
  31.     p_combobox->addItems(strings);
  32.     Q_ASSERT(p_combobox->model()->rowCount() == 4);
  33.     QObject::connect(p_reverse_items_button, &QAbstractButton::clicked, p_combobox, [&]
  34.     {
  35.         //auto p_current_model = qobject_cast<QStringListModel*>(p_combobox->model());
  36.         //auto items = p_current_model->stringList();
  37.         auto& items = is_current_strings ? strings : numbers;
  38.         std::reverse(items.begin(), items.end());
  39.         p_combobox->clear();
  40.         p_combobox->addItems(items);
  41.         //p_current_model->setStringList(items);
  42.     });
  43.  
  44.     auto p_change_model_button = new QPushButton("Set another model", &main_widget);
  45.     p_layout->addWidget(p_change_model_button);
  46.     QObject::connect(p_change_model_button, &QAbstractButton::clicked, p_combobox, [&]
  47.     {
  48.         is_current_strings = !is_current_strings;
  49.         auto& items = is_current_strings ? strings : numbers;
  50.         p_combobox->clear();
  51.         p_combobox->addItems(items);
  52.         //auto p_current_model = qobject_cast<QStringListModel*>(p_combobox->model());
  53.         //p_combobox->setModel(p_current_model == &strings_model ? &numbers_model : &strings_model);
  54.     });
  55.  
  56.  
  57.     main_widget.setLayout(p_layout);
  58.     main_widget.show();
  59.  
  60.     return a.exec();
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement