Просмотр исходного кода

ENH: Added currentUserDataAsString property to ctkComboBox

It is useful so that the user data of the combobox items can be saved in application settings instead of the raw index (0, 1, etc.). An example of this is the values of QMessageBox button codes based on a selection in a message box (-1 for invalid, 16384 for Yes, 65536 for No, etc.)
Csaba Pitner лет назад: 7
Родитель
Сommit
d18c1a4eb3
2 измененных файлов с 33 добавлено и 2 удалено
  1. 22 0
      Libs/Widgets/ctkComboBox.cpp
  2. 11 2
      Libs/Widgets/ctkComboBox.h

+ 22 - 0
Libs/Widgets/ctkComboBox.cpp

@@ -366,3 +366,25 @@ void ctkComboBox::wheelEvent(QWheelEvent* event)
     event->ignore();
     }
 }
+
+// -------------------------------------------------------------------------
+QString ctkComboBox::currentUserDataAsString()const
+{
+  return this->itemData(this->currentIndex()).toString();
+}
+
+// -------------------------------------------------------------------------
+void ctkComboBox::setCurrentUserDataAsString(QString userData)
+{
+  for (int index=0; index<this->count(); ++index)
+    {
+    QString currentItemUserData = this->itemData(index).toString();
+    if (!userData.compare(currentItemUserData))
+      {
+      this->setCurrentIndex(index);
+      return;
+      }
+    }
+
+  qWarning() << Q_FUNC_INFO << ": No item found with user data string " << userData;
+}

+ 11 - 2
Libs/Widgets/ctkComboBox.h

@@ -52,10 +52,12 @@ class CTK_WIDGETS_EXPORT ctkComboBox : public QComboBox
   /// ScrollOn by default.
   /// /sa scrollWheelEffect, setScrollWheelEffect
   Q_PROPERTY(ScrollEffect scrollWheelEffect READ scrollWheelEffect WRITE setScrollWheelEffect)
+  /// Current item's user data as string (Qt::UserRole role)
+  Q_PROPERTY(QString currentUserDataAsString READ currentUserDataAsString WRITE setCurrentUserDataAsString)
 
   Q_ENUMS(ScrollEffect);
 public:
-  /// Constructor, build a ctkComboBox that behave like QComboBox.
+  /// Constructor, build a ctkComboBox that behaves like QComboBox.
   explicit ctkComboBox(QWidget* parent = 0);
   virtual ~ctkComboBox();
 
@@ -87,7 +89,7 @@ public:
     /// Scrolling is only possible if the combobox has the focus.
     /// The focus policy is automatically set to Qt::StrongFocus
     ScrollWithFocus,
-    /// Scrolling is not possible when the combobox is inside a scrollarea with
+    /// Scrolling is not possible when the combobox is inside a scroll area with
     /// a visible vertical scrollbar.
     ScrollWithNoVScrollBar
   };
@@ -103,6 +105,13 @@ public:
   /// Reimplemented for internal reasons
   virtual QSize sizeHint()const;
 
+  /// Get current item's user data as string
+  QString currentUserDataAsString()const;
+
+public slots:
+  /// Set current item based on user data
+  void setCurrentUserDataAsString(QString userData);
+
 protected:
   /// Reimplemented for internal reasons
   virtual void paintEvent(QPaintEvent* event);