问题
The application GUI I working requires a combo box for user to select item. When the application starts, the combo box will show a hint text something like "Please select" instead of showing the first item of the combo box. I cannot find any method for setting the hint text in http://doc.qt.io/qt-5/qcombobox.html#currentText-prop.
Thank in advance!
回答1:
There is an elegant solution if the QComboBox is editable:
myQComboBox->lineEdit()->setPlaceHolderText("Please select");
QComboBoxes that are not editable do not have QLineEdits in them, so this would not work on those.
回答2:
There is no way to set place holder text for QComboBox. But you can solve this problem. Use setEditText( const QString& ) slot for setting your text. If user selects an item in comboBox, item's text will be set. But if user selects the text, deletes it, and selects other control element (combo box looses its focus), your text won't be there anymore. Its possible to solve by inheriting from QComboBox, and reimplementing focusOutEvent(...), where you check: if ( currentIndex() == -1 ) setEditText( tr( "Please select" ) );. And dont forget to call QComboBox::focusOutEvent(...) first.
来源:https://stackoverflow.com/questions/6327964/qcombobox-how-to-set-hint-text-on-combo-box