Difference between revisions of "Select an Entry or Add a New One ComboBox"

From Qt Wiki
Jump to: navigation, search
(Decode HTML entity names)
(clean-up)
 
Line 1: Line 1:
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}
 
 
 
[[Category:HowTo]]
 
[[Category:HowTo]]
 
[[Category:snippets]]
 
[[Category:snippets]]
 
= How to select a specific text entry (or add it if does not exist) in a combo box =
 
 
 
The following method acts on a combo box searching for a specified text string and:
 
The following method acts on a combo box searching for a specified text string and:
 
* if the string is present select it
 
* if the string is present select it
Line 12: Line 7:
 
In the following piece of code ''myText'' is the QString searched for and ''combo'' is a reference to the combo box.
 
In the following piece of code ''myText'' is the QString searched for and ''combo'' is a reference to the combo box.
  
<code> bool found = false;
+
<code>
for( int i = 0; i < combo->count() && ! found ; i++ )
+
bool found = false;
  if( combo->itemText( i ) == myText ){
+
for( int i = 0; i < combo->count() && ! found ; i++ ) {
combo->setCurrentIndex( i );
+
  if( combo->itemText( i ) == myText ) {
found = true;
+
  combo->setCurrentIndex( i );
 +
  found = true;
 
  }
 
  }
 
+
}
if( ! found ){
+
if (!found ) {
 
  int index = combo->count();
 
  int index = combo->count();
 
  combo->addItem( myText );
 
  combo->addItem( myText );
 
+
}
 
combo->setCurrentIndex( index );
 
combo->setCurrentIndex( index );
 +
</code>

Latest revision as of 14:20, 24 March 2016

The following method acts on a combo box searching for a specified text string and:

  • if the string is present select it
  • if the string is not present add it to the combo box model

In the following piece of code myText is the QString searched for and combo is a reference to the combo box.

bool found = false; for( int i = 0; i < combo->count() && ! found ; i++ ) {

if( combo->itemText( i ) == myText ) {
 combo->setCurrentIndex( i );
 found = true;
}

} if (!found ) {

int index = combo->count();
combo->addItem( myText );

} combo->setCurrentIndex( index );