ctkMenuComboBox.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QAbstractItemView>
  16. #include <QActionEvent>
  17. #include <QCompleter>
  18. #include <QDebug>
  19. #include <QEvent>
  20. #include <QHBoxLayout>
  21. #include <QLineEdit>
  22. #include <QStringList>
  23. #include <QStringListModel>
  24. #include <QToolButton>
  25. // CTK includes
  26. #include "ctkCompleter.h"
  27. #include "ctkSearchBox.h"
  28. #include "ctkMenuComboBox_p.h"
  29. // -------------------------------------------------------------------------
  30. ctkMenuComboBoxInternal::ctkMenuComboBoxInternal()
  31. {
  32. }
  33. // -------------------------------------------------------------------------
  34. ctkMenuComboBoxInternal::~ctkMenuComboBoxInternal()
  35. {
  36. }
  37. // -------------------------------------------------------------------------
  38. void ctkMenuComboBoxInternal::showPopup()
  39. {
  40. QMenu* menu = this->Menu.data();
  41. if (!menu)
  42. {
  43. return;
  44. }
  45. menu->popup(this->mapToGlobal(this->rect().bottomLeft()));
  46. static int minWidth = menu->sizeHint().width();
  47. menu->setFixedWidth(qMax(this->width(), minWidth));
  48. emit popupShown();
  49. }
  50. // -------------------------------------------------------------------------
  51. QSize ctkMenuComboBoxInternal::minimumSizeHint()const
  52. {
  53. // Cached QComboBox::minimumSizeHint is not recomputed when the current
  54. // index change, however QComboBox::sizeHint is. Use it instead.
  55. return this->sizeHint();
  56. }
  57. // -------------------------------------------------------------------------
  58. ctkMenuComboBoxPrivate::ctkMenuComboBoxPrivate(ctkMenuComboBox& object)
  59. :q_ptr(&object)
  60. {
  61. this->MenuComboBox = 0;
  62. this->SearchCompleter = 0;
  63. this->EditBehavior = ctkMenuComboBox::NotEditable;
  64. this->IsDefaultTextCurrent = true;
  65. this->IsDefaultIconCurrent = true;
  66. }
  67. // -------------------------------------------------------------------------
  68. void ctkMenuComboBoxPrivate::init()
  69. {
  70. Q_Q(ctkMenuComboBox);
  71. this->setParent(q);
  72. QHBoxLayout* layout = new QHBoxLayout(q);
  73. layout->setContentsMargins(0,0,0,0);
  74. layout->setSizeConstraint(QLayout::SetMinimumSize);
  75. layout->setSpacing(0);
  76. // SearchButton
  77. this->SearchButton = new QToolButton();
  78. this->SearchButton->setText(q->tr("Search"));
  79. this->SearchButton->setIcon(QIcon(":/Icons/search.svg"));
  80. this->SearchButton->setCheckable(true);
  81. this->SearchButton->setAutoRaise(true);
  82. layout->addWidget(this->SearchButton);
  83. q->connect(this->SearchButton, SIGNAL(toggled(bool)),
  84. this, SLOT(setComboBoxEditable(bool)));
  85. // MenuComboBox
  86. this->MenuComboBox = new ctkMenuComboBoxInternal();
  87. this->MenuComboBox->setMinimumContentsLength(12);
  88. layout->addWidget(this->MenuComboBox);
  89. this->MenuComboBox->installEventFilter(q);
  90. this->MenuComboBox->setInsertPolicy(QComboBox::NoInsert);
  91. this->MenuComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
  92. this->MenuComboBox->addItem(this->DefaultIcon, this->DefaultText);
  93. q->connect(this->MenuComboBox, SIGNAL(popupShown()),
  94. q, SIGNAL(popupShown()));
  95. this->SearchCompleter = new ctkCompleter(QStringList(), this->MenuComboBox);
  96. this->SearchCompleter->popup()->setParent(q);
  97. this->SearchCompleter->setCaseSensitivity(Qt::CaseInsensitive);
  98. this->SearchCompleter->setModelFiltering(ctkCompleter::FilterWordStartsWith);
  99. q->connect(this->SearchCompleter, SIGNAL(activated(QString)),
  100. this, SLOT(onCompletion(QString)));
  101. // Automatically set the minimumSizeHint of the layout to the widget
  102. layout->setSizeConstraint(QLayout::SetMinimumSize);
  103. // Behave like a QComboBox
  104. q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed,
  105. QSizePolicy::ComboBox));
  106. q->setDefaultText(ctkMenuComboBox::tr("Search..."));
  107. }
  108. // ------------------------------------------------------------------------
  109. QAction* ctkMenuComboBoxPrivate::actionByTitle(const QString& text, const QMenu* parentMenu)
  110. {
  111. if (!parentMenu || parentMenu->title() == text)
  112. {
  113. return 0;
  114. }
  115. foreach(QAction* action, parentMenu->actions())
  116. {
  117. if (!action->menu() && action->text().toLower() == text.toLower())
  118. {
  119. return action;
  120. }
  121. if (action->menu())
  122. {
  123. QAction* subAction = this->actionByTitle(text, action->menu());
  124. if(subAction)
  125. {
  126. return subAction;
  127. }
  128. }
  129. }
  130. return 0;
  131. }
  132. // ------------------------------------------------------------------------
  133. void ctkMenuComboBoxPrivate::setCurrentText(const QString& newCurrentText)
  134. {
  135. if (this->MenuComboBox->lineEdit())
  136. {
  137. static_cast<ctkSearchBox*>(this->MenuComboBox->lineEdit())
  138. ->setPlaceholderText(newCurrentText);
  139. }
  140. this->MenuComboBox->setItemText(this->MenuComboBox->currentIndex(),
  141. newCurrentText);
  142. }
  143. // ------------------------------------------------------------------------
  144. QString ctkMenuComboBoxPrivate::currentText()const
  145. {
  146. return this->MenuComboBox->itemText(this->MenuComboBox->currentIndex());
  147. }
  148. // ------------------------------------------------------------------------
  149. QIcon ctkMenuComboBoxPrivate::currentIcon()const
  150. {
  151. return this->MenuComboBox->itemIcon(this->MenuComboBox->currentIndex());
  152. }
  153. // ------------------------------------------------------------------------
  154. void ctkMenuComboBoxPrivate::setCurrentIcon(const QIcon& newCurrentIcon)
  155. {
  156. this->MenuComboBox->setItemIcon(this->MenuComboBox->currentIndex(),
  157. newCurrentIcon);
  158. }
  159. // -------------------------------------------------------------------------
  160. void ctkMenuComboBoxPrivate::setComboBoxEditable(bool edit)
  161. {
  162. Q_Q(ctkMenuComboBox);
  163. if(edit)
  164. {
  165. if (!this->MenuComboBox->lineEdit())
  166. {
  167. ctkSearchBox* line = new ctkSearchBox();
  168. this->MenuComboBox->setLineEdit(line);
  169. if (q->isSearchIconVisible())
  170. {
  171. this->MenuComboBox->lineEdit()->selectAll();
  172. this->MenuComboBox->setFocus();
  173. }
  174. q->connect(line, SIGNAL(editingFinished()),
  175. q,SLOT(onEditingFinished()));
  176. }
  177. this->MenuComboBox->setCompleter(this->SearchCompleter);
  178. }
  179. this->MenuComboBox->setEditable(edit);
  180. }
  181. // -------------------------------------------------------------------------
  182. void ctkMenuComboBoxPrivate::onCompletion(const QString& text)
  183. {
  184. Q_Q(ctkMenuComboBox);
  185. // In Qt5, when QCompleter sends its activated() signal, QComboBox sets
  186. // its current index to the activated item, if found. Work around that behavior
  187. // by re-selecting the original item.
  188. this->MenuComboBox->setCurrentIndex(0);
  189. // Set text to the completed string
  190. if (this->MenuComboBox->lineEdit())
  191. {
  192. this->MenuComboBox->lineEdit()->setText(text);
  193. }
  194. q->onEditingFinished();
  195. }
  196. // -------------------------------------------------------------------------
  197. void ctkMenuComboBoxPrivate::addAction(QAction *action)
  198. {
  199. if (action->menu())
  200. {
  201. this->addMenuToCompleter(action->menu());
  202. }
  203. else
  204. {
  205. this->addActionToCompleter(action);
  206. }
  207. }
  208. // -------------------------------------------------------------------------
  209. void ctkMenuComboBoxPrivate::addMenuToCompleter(QMenu* menu)
  210. {
  211. Q_Q(ctkMenuComboBox);
  212. menu->installEventFilter(q);
  213. // Bug QT : see this link for more details
  214. // https://bugreports.qt.nokia.com/browse/QTBUG-20929?focusedCommentId=161370#comment-161370
  215. // if the submenu doesn't have a parent, the submenu triggered(QAction*)
  216. // signal is not propagated. So we listened this submenu to fix the bug.
  217. QObject* emptyObject = 0;
  218. if(menu->parent() == emptyObject)
  219. {
  220. q->connect(menu, SIGNAL(triggered(QAction*)),
  221. q, SLOT(onActionSelected(QAction*)), Qt::UniqueConnection);
  222. }
  223. foreach (QAction* action, menu->actions())
  224. {
  225. this->addAction(action);
  226. }
  227. }
  228. // -------------------------------------------------------------------------
  229. void ctkMenuComboBoxPrivate::addActionToCompleter(QAction *action)
  230. {
  231. QStringListModel* model = qobject_cast<QStringListModel* >(
  232. this->SearchCompleter->sourceModel());
  233. Q_ASSERT(model);
  234. QModelIndex start = model->index(0,0);
  235. QModelIndexList indexList = model->match(start, 0, action->text(), 1, Qt::MatchFixedString|Qt::MatchWrap);
  236. if (indexList.count())
  237. {
  238. return;
  239. }
  240. int actionCount = model->rowCount();
  241. model->insertRow(actionCount);
  242. QModelIndex index = model->index(actionCount, 0);
  243. model->setData(index, action->text());
  244. }
  245. // ------------------------------------------------------------------------
  246. void ctkMenuComboBoxPrivate::removeActionToCompleter(QAction *action)
  247. {
  248. QStringListModel* model = qobject_cast<QStringListModel* >(
  249. this->SearchCompleter->sourceModel());
  250. Q_ASSERT(model);
  251. if (!model->stringList().contains(action->text()) )
  252. {
  253. return;
  254. }
  255. // Maybe the action is present multiple times in different submenus
  256. // Don't remove its entry from the completer model if there are still some action instances
  257. // in the menus.
  258. if (this->actionByTitle(action->text(), this->Menu.data()))
  259. {
  260. return;
  261. }
  262. QModelIndex start = model->index(0,0);
  263. QModelIndexList indexList = model->match(start, 0, action->text());
  264. Q_ASSERT(indexList.count() == 1);
  265. foreach (QModelIndex index, indexList)
  266. {
  267. // Search completer model is a flat list
  268. model->removeRow(index.row());
  269. }
  270. }
  271. // ------------------------------------------------------------------------
  272. ctkMenuComboBox::ctkMenuComboBox(QWidget* _parent)
  273. :QWidget(_parent)
  274. , d_ptr(new ctkMenuComboBoxPrivate(*this))
  275. {
  276. Q_D(ctkMenuComboBox);
  277. d->init();
  278. }
  279. // ------------------------------------------------------------------------
  280. ctkMenuComboBox::~ctkMenuComboBox()
  281. {
  282. }
  283. // ------------------------------------------------------------------------
  284. void ctkMenuComboBox::setMenu(QMenu* menu)
  285. {
  286. Q_D(ctkMenuComboBox);
  287. if (d->Menu.data() == menu)
  288. {
  289. return;
  290. }
  291. if (d->Menu)
  292. {
  293. this->removeAction(d->Menu.data()->menuAction());
  294. QObject::disconnect(d->Menu.data(),SIGNAL(triggered(QAction*)),
  295. this,SLOT(onActionSelected(QAction*)));
  296. }
  297. d->Menu = menu;
  298. d->MenuComboBox->Menu = menu;
  299. d->addMenuToCompleter(menu);
  300. if (d->Menu)
  301. {
  302. this->addAction(d->Menu.data()->menuAction());
  303. QObject::connect(d->Menu.data(),SIGNAL(triggered(QAction*)),
  304. this,SLOT(onActionSelected(QAction*)), Qt::UniqueConnection);
  305. }
  306. }
  307. // -------------------------------------------------------------------------
  308. QMenu* ctkMenuComboBox::menu()const
  309. {
  310. Q_D(const ctkMenuComboBox);
  311. return d->Menu.data();
  312. }
  313. // -------------------------------------------------------------------------
  314. void ctkMenuComboBox::setDefaultText(const QString& newDefaultText)
  315. {
  316. Q_D(ctkMenuComboBox);
  317. d->DefaultText = newDefaultText;
  318. if (d->IsDefaultTextCurrent)
  319. {
  320. d->setCurrentText(d->DefaultText);
  321. }
  322. }
  323. // -------------------------------------------------------------------------
  324. QString ctkMenuComboBox::defaultText()const
  325. {
  326. Q_D(const ctkMenuComboBox);
  327. return d->DefaultText;
  328. }
  329. // -------------------------------------------------------------------------
  330. void ctkMenuComboBox::setDefaultIcon(const QIcon& newIcon)
  331. {
  332. Q_D(ctkMenuComboBox);
  333. d->DefaultIcon = newIcon;
  334. if (d->IsDefaultIconCurrent)
  335. {
  336. d->setCurrentIcon(d->DefaultIcon);
  337. }
  338. }
  339. // -------------------------------------------------------------------------
  340. QIcon ctkMenuComboBox::defaultIcon()const
  341. {
  342. Q_D(const ctkMenuComboBox);
  343. return d->DefaultIcon;
  344. }
  345. // -------------------------------------------------------------------------
  346. void ctkMenuComboBox::setEditableBehavior(ctkMenuComboBox::EditableBehavior edit)
  347. {
  348. Q_D(ctkMenuComboBox);
  349. d->EditBehavior = edit;
  350. this->disconnect(d->MenuComboBox, SIGNAL(popupShown()),
  351. d, SLOT(setComboBoxEditable()));
  352. switch (edit)
  353. {
  354. case ctkMenuComboBox::Editable:
  355. d->MenuComboBox->setContextMenuPolicy(Qt::DefaultContextMenu);
  356. d->setComboBoxEditable(true);
  357. break;
  358. case ctkMenuComboBox::NotEditable:
  359. d->MenuComboBox->setContextMenuPolicy(Qt::DefaultContextMenu);
  360. d->setComboBoxEditable(false);
  361. break;
  362. case ctkMenuComboBox::EditableOnFocus:
  363. d->setComboBoxEditable(this->hasFocus());
  364. // Here we set the context menu policy to fix a crash on the right click.
  365. // Opening the context menu removes the focus on the line edit,
  366. // the comboBox becomes not editable, and the line edit is deleted.
  367. // The opening of the context menu is done in the line edit and lead to
  368. // a crash because it infers that the line edit is valid. Another fix
  369. // could be to delete the line edit later (deleteLater()).
  370. d->MenuComboBox->setContextMenuPolicy(Qt::NoContextMenu);
  371. break;
  372. case ctkMenuComboBox::EditableOnPopup:
  373. d->setComboBoxEditable(false);
  374. this->connect(d->MenuComboBox, SIGNAL(popupShown()),
  375. d, SLOT(setComboBoxEditable()));
  376. // Same reason as in ctkMenuComboBox::EditableOnFocus.
  377. d->MenuComboBox->setContextMenuPolicy(Qt::NoContextMenu);
  378. break;
  379. }
  380. }
  381. // -------------------------------------------------------------------------
  382. ctkMenuComboBox::EditableBehavior ctkMenuComboBox::editableBehavior()const
  383. {
  384. Q_D(const ctkMenuComboBox);
  385. return d->EditBehavior;
  386. }
  387. // -------------------------------------------------------------------------
  388. void ctkMenuComboBox::setSearchIconVisible(bool state)
  389. {
  390. Q_D(ctkMenuComboBox);
  391. d->SearchButton->setVisible(state);
  392. }
  393. // -------------------------------------------------------------------------
  394. bool ctkMenuComboBox::isSearchIconVisible() const
  395. {
  396. Q_D(const ctkMenuComboBox);
  397. return d->SearchButton->isVisibleTo(const_cast<ctkMenuComboBox*>(this));
  398. }
  399. // -------------------------------------------------------------------------
  400. void ctkMenuComboBox::setToolButtonStyle(Qt::ToolButtonStyle style)
  401. {
  402. Q_D(ctkMenuComboBox);
  403. d->SearchButton->setToolButtonStyle(style);
  404. }
  405. // -------------------------------------------------------------------------
  406. Qt::ToolButtonStyle ctkMenuComboBox::toolButtonStyle() const
  407. {
  408. Q_D(const ctkMenuComboBox);
  409. return d->SearchButton->toolButtonStyle();
  410. }
  411. // -------------------------------------------------------------------------
  412. void ctkMenuComboBox::setMinimumContentsLength(int characters)
  413. {
  414. Q_D(ctkMenuComboBox);
  415. d->MenuComboBox->setMinimumContentsLength(characters);
  416. }
  417. // -------------------------------------------------------------------------
  418. QComboBox* ctkMenuComboBox::menuComboBoxInternal() const
  419. {
  420. Q_D(const ctkMenuComboBox);
  421. return d->MenuComboBox;
  422. }
  423. // -------------------------------------------------------------------------
  424. QToolButton* ctkMenuComboBox::toolButtonInternal() const
  425. {
  426. Q_D(const ctkMenuComboBox);
  427. return d->SearchButton;
  428. }
  429. // -------------------------------------------------------------------------
  430. ctkCompleter* ctkMenuComboBox::searchCompleter() const
  431. {
  432. Q_D(const ctkMenuComboBox);
  433. return d->SearchCompleter;
  434. }
  435. // -------------------------------------------------------------------------
  436. void ctkMenuComboBox::onActionSelected(QAction* action)
  437. {
  438. Q_D(ctkMenuComboBox);
  439. /// Set the action selected in the combobox.
  440. d->IsDefaultTextCurrent = true;
  441. QString newText = d->DefaultText;
  442. if (action && !action->text().isEmpty())
  443. {
  444. newText = action->text();
  445. d->IsDefaultTextCurrent = false;
  446. }
  447. d->setCurrentText(newText);
  448. d->IsDefaultIconCurrent = true;
  449. QIcon newIcon = d->DefaultIcon;
  450. if (action && !action->icon().isNull())
  451. {
  452. d->IsDefaultIconCurrent = false;
  453. newIcon = action->icon();
  454. }
  455. d->setCurrentIcon(newIcon);
  456. d->MenuComboBox->clearFocus();
  457. emit ctkMenuComboBox::actionChanged(action);
  458. }
  459. // -------------------------------------------------------------------------
  460. void ctkMenuComboBox::clearActiveAction()
  461. {
  462. this->onActionSelected(0);
  463. }
  464. // -------------------------------------------------------------------------
  465. void ctkMenuComboBox::onEditingFinished()
  466. {
  467. Q_D(ctkMenuComboBox);
  468. if (!d->MenuComboBox->lineEdit())
  469. {
  470. return;
  471. }
  472. QAction* action = d->actionByTitle(d->MenuComboBox->lineEdit()->text(), d->Menu.data());
  473. if (!action)
  474. {
  475. return;
  476. }
  477. if (this->isSearchIconVisible())
  478. {
  479. d->SearchButton->setChecked(false);
  480. }
  481. action->trigger();
  482. }
  483. // -------------------------------------------------------------------------
  484. bool ctkMenuComboBox::eventFilter(QObject* target, QEvent* event)
  485. {
  486. Q_D(ctkMenuComboBox);
  487. if (target == d->MenuComboBox)
  488. {
  489. if (event->type() == QEvent::Resize)
  490. {
  491. this->layout()->invalidate();
  492. }
  493. if (event->type() == QEvent::FocusIn &&
  494. d->EditBehavior == ctkMenuComboBox::EditableOnFocus)
  495. {
  496. d->setComboBoxEditable(true);
  497. }
  498. if (event->type() == QEvent::FocusOut &&
  499. (d->EditBehavior == ctkMenuComboBox::EditableOnFocus ||
  500. d->EditBehavior == ctkMenuComboBox::EditableOnPopup))
  501. {
  502. d->setComboBoxEditable(false);
  503. }
  504. }
  505. else if (event->type() == QEvent::ActionAdded)
  506. {
  507. QActionEvent* actionEvent = static_cast<QActionEvent *>(event);
  508. d->addAction(actionEvent->action());
  509. }
  510. else if (event->type() == QEvent::ActionRemoved)
  511. {
  512. QActionEvent* actionEvent = static_cast<QActionEvent *>(event);
  513. d->removeActionToCompleter(actionEvent->action());
  514. }
  515. return this->Superclass::eventFilter(target, event);
  516. }