Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-1556

Support "instruction"-item in QComboBox

    XMLWordPrintable

Details

    • 360df2cf74410b05d1cab0192f2d0ff5a39db59e (qt/qtbase/5.15)

    Description

      A typical usecase for QComboBox is to display them initially with an "instruction" text, i.e. "Select country...". That text itself is not selectable, and disappears when the combobox is popped up the first time. The following subclass implements this behavior, but having this supported by QComboBox directly would be nice:

      #include <QtGui>
      
      class ComboBox : public QComboBox
      {
          Q_OBJECT
      public:
          ComboBox()
          {
              
          }
      
          void setDummyItem(const QString &text)
          {
              dummyText = text;
          }
      
          void showPopup()
          {
              removeDummy();
              QComboBox::showPopup();
          }
      
      protected:
          void showEvent(QShowEvent *e)
          {
              addDummy();
              QComboBox::showEvent(e);
          }
      
      private slots:
          void removeDummy()
          {
              if (!dummyText.isNull() && itemText(0) == dummyText) {
                  removeItem(0);
                  disconnect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(removeDummy()));
              }
          }
      
      private:
          void addDummy()
          {
              if (!dummyText.isNull() && itemText(0) != dummyText) {
                  insertItem(0, dummyText);
                  setCurrentItem(0);
                  connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(removeDummy()));
              }
          }
      
          QString dummyText;
      };
      
      #include "main.moc"
      
      int main(int argc, char *argv[])
      {
          QApplication a(argc, argv);
      
          ComboBox cb;
          cb.addItems(QStringList() << "Euro" << "USD" << "Yen" << "GBP");
          cb.setDummyItem("Select Currency...");
          cb.show();
          
      
          return a.exec();
      }
      

      Attachments

        Issue Links

          No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

              Unassigned Unassigned
              vhilshei Volker Hilsheimer
              Votes:
              1 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Gerrit Reviews

                  There are no open Gerrit changes