ctkMenuComboBox.cpp 16 KB

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