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

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
Line 1: Line 1:
=How to select a specific text entry (or add it if does not exist) in a combo box=
[[Category:HowTo]]<br />[[Category:snippets]]


The following method acts on a combo box searching for a specified text string and:
= How to select a specific text entry (or add it if does not exist) in a combo box =


* if the string is present select it
The following method acts on a combo box searching for a specified text string and:<br />* if the string is present select it<br />* if the string is not present add it to the combo box model
* 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.
In the following piece of code ''myText'' is the QString searched for and ''combo'' is a reference to the combo box.


===Categories:===
<code> bool found = false;<br /> for( int i = 0; i &lt; combo-&gt;count() &amp;&amp; ! found ; i++ )<br /> if( combo-&gt;itemText( i ) == myText ){<br /> combo-&gt;setCurrentIndex( i );<br /> found = true;<br /> }


* [[:Category:HowTo|HowTo]]
if( ! found ){<br /> int index = combo-&gt;count();<br /> combo-&gt;addItem( myText );
* [[:Category:snippets|snippets]]
 
combo-&gt;setCurrentIndex( index );

Revision as of 06:26, 24 February 2015


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:
* 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 );