User Tools

Site Tools


k16:k16.13:start

16.13 ComboBox

The component ComboBox (gb.qt4) is a combination of a Textbox and a (PopUp-)ListBox. The field of application for a ComboBox is the input of data as a character string. Either select an element from the list box, which is then displayed in the text box, or enter text in the text box.

Only if the property ComboBox. ReadOnly has been set to True, will the entries become valid data that you can continue to work with in the program. Otherwise the data must always be checked!

16.13.1 Properties and methods ComboBox

Selected properties and methods of a ComboBox are listed and described in a table:

PropertyTypeDescription
Count IntegerSpecifies the number of elements in the popup list box.
CurrentComboBox. ItemReturns the current selected item in the popup list box. Combobox.Item represents an entry in the popup list box with the property Text.
IndexIntegerIndicates the index of the currently selected element in the popup list box.
LengthIntegerDetermines the length of the selected text in the TextBox.
ListArrayStores the contents of the list box in a string array or fills the list box with the contents of a string array.
MaxlengthIntegerDetermines the maximum permissible length of the text in the text field or specifies the maximum permissible length of the text in the text field.
PasswordBooleanIndicates whether characters are entered into the text field hidden and replaced by asterisks.
PosIntegerDetermines the position of the cursor in the text field or determines the position of the cursor in the text field.
ReadOnlyBooleanShows whether the contents of the ComboBox are only read or whether the text field is editable or not.
SortedBooleanSpecifies whether or not the items are displayed sorted in the list box.
TextStringReturns the displayed text in the text box or writes the text to the text box. (Synonym: ComboBox.Item.Text)
SelectedBooleanSpecifies whether or not a text is selected in the combo box.
SelectionTextBox. SelectionReturns an object for managing the selected text.

Table 16.13.1.1: Overview of ComboBox component properties

TextBox.Selection has the following properties:

  • TextBox.Selection.Text: Returns the selected text or zero if no text is selected.
  • TextBox.Selection.Start: Returns the starting position of the selected text or a -1 if no text is marked.
  • TextBox.Selection.Length: Returns the length of the currently selected text or 0 if no text is selected.

The TextBox.Selection.Hide method hides the selected text in the TextBox.

Like any other TextBox, the TextBox of a ComboBox has a standard context menu, which you can call up with a click of the right mouse button.

A brief description of the ComboBox component's methods can be found in the following table:

MethodDescription
Add (Item As String[, Index As Integer] Inserts an element (item) into the ComboBox list. If the optional value Index is set, the insertion takes place at the position defined by the index, otherwise at the end of the list.
Insert (Text as String) Inserts a string into the empty TextBox or supplements the existing text in the TextBox.
Clear () Deletes the contents of the ComboBox list.
Find (Item As String) Finds an element in the popup list box and returns the corresponding index (type integer) or -1 if the element is not found in the popup list box.
Popup () Opens the ComboBox popup menu.
Remove (Index As Integer) Deletes the indexed element in the ComboBox list.
Select ([ Start As Integer, Length As Integer]) Returns the text from the start position and in the specified length. Without (optional) arguments, the entire text is returned.
SelectAll () Selects the entire text and returns it.
Unselect () Cancels the selection of the selected text in the combo box.

Table 16.13.1.2: Overview of methods of the ComboBox class

16.13.2 Events ComboBox

The special events of the ComboBox component and additional comments can be found here:

EventDescription
ActivateIs triggered when the ComboBox has the focus and the Enter key is pressed.
ChangeIs triggered when the text in the combo box is changed and the ComboBox. ReadOnly property is set to False.
ClickIs triggered when an item is selected in the pop-up list.

Notes on the ComboBox_Click () event

  • The click event is triggered when the index or text property has been set, even if the new value is the same as the old one! This does not apply to the use of the component gb.qt4.
  • The click event is not triggered when you set the index to -1 or when you populate the Text property with something that is not already in ComboBox list.
  • The click event is not triggered if the content of the list has been changed by adding, removing or deleting or if you change the list property.

16.13.3 ComboBox lists

Before you can use a ComboBox to enter data (data type string) in a program, you must fill in the list (data type array) from which the user can make a selection. Which of the approaches you prefer depends on the tasks to be solved and the value of the ComboBox.Read-only property. First, individual approaches are presented and then implemented with examples:

  • Insert elements into the (inline) array list,
  • Paste elements into the list with the add method,
  • Insert the elements into an explicitly declared array, which is later passed as list content.

Importing elements of a list, for example

  • from a binary, gambas-specific file,
  • from an XML file, csv file or a simple text file,
  • from a database table (set filter in SQL statement for exactly one field)
  • from program-internal calculations (? case differentiations),
  • from a generated interface list or
  • from a generated list of printers available in the system.

16.13.4 Example 1 - Filling the ComboBox List

[1] ' Gambas class file
[2] 
[3] Public Sub _new()
[4]   SetCBList()  
[5] End ' _new()
[6] 
[7] Public Sub Form_Open()
[8]   FMain.Center
[9]   FMain.Resizable = False
[10] End ' Form_Open()
[11] 
[12] Public Sub SetCBList()
[13]   Dim aMatrix As New String[]
[14]   
[15]   ComboBox1.List = ["Element2", "Element1"] ' Inline-Array
[16]   ComboBox1.Add("Element3")
[17]   ComboBox1.Add("Element5")
[18]   ComboBox1.Add("Element4")
[19]   aMatrix.Add("Element6")
[20]   aMatrix.Add("Element7")  
[21]   ComboBox1.List = ComboBox1.List.Insert(aMatrix)
[22]   ComboBox1.Sorted = True
[23]   ComboBox1.Text = ComboBox1.List[0]
[24] 
[25] End ' SetList()

You should transfer the call of SetCBList () to the _new procedure, because the statements

ComboBox1.Text = ComboBox1.List[0] ' Display first entry in the CB list
ComboBox1.Text = ComboBox1.List[ComboBox1.List.Max] ' Display last entry in the CB list

would trigger the click event!

Comments:

  • The list is filled in line 15 with 2 elements (inline array).
  • The list is extended by 3 entries.
  • In lines 19 and 20 2 elements are inserted into the array aMatrix.
  • The content of the array aMatrix is inserted in line 21 at the end of the list.
  • The entries in the list are then sorted.

16.13.5 Example 2 - ComboBox with history

In this example, a ComboBox is given a history. This reads the last path entries into the list of the ComboBox at program start. Newer paths are dynamically inserted into the list at runtime and overwrite older entries. The source code shows that the current list content is stored in a configuration file because the component gb. settings is used, which implicitly provides all file operations for exporting and importing the list content.

' Gambas class file
 
Private $aFavorites As String[]
Private Const $iCount As Integer = 4
 
Public Sub Form_Open()
 
  FMain.Center
  $aFavorites = Settings["Favorites"] ' Import
' Konfigurationsdatei: /home/hans/.config/gambas3/ComboBoxFavourites.conf
  If Not $aFavorites Then $aFavorites = New String[]
  ReloadFavorites()
 
End ' Form_Open()
 
Public Sub btnSelect_Click()
' Create only existing directories
 
  If Not IsDir(cmbPath.Text) Then
    Message.Error(("The specified path is not a directory!"))
    cmbPath.SetFocus
    Return
  Endif ' Not IsDir(cmbPath.Text) ?
 
' Do not allow duplicates and limit history
  If $aFavorites.Count <= $iCount Then 
     If Not $aFavorites.Exist(cmbPath.Text) Then $aFavorites.Add(cmbPath.Text)
  Else
     If Not $aFavorites.Exist(cmbPath.Text) Then
        $aFavorites.Remove(0)
        $aFavorites.Add(cmbPath.Text)
     Endif
  Endif
  ReloadFavorites()
 
End ' btnSelect_Click()
 
Public Sub Form_Close()
  Settings["Favorites"] = $aFavorites ' Export
End ' Form_Close()
 
'********************************************************************************************
 
Private Sub ReloadFavorites()
' An empty entry for input in the TextBox, then the favorites
  cmbPath.List = [""].Insert($aFavorites)
End ' ReloadFavorites()
 
Public Sub dchPath_Change()
  cmbPath.Text = dchPath.Value
End ' dchPath_Change()
 
Public Sub cmbPath_Activate()
  btnSelect_Click()
End ' cmbPath_Activate()

CB1

Figure 16.13.5.1: ComboBox with history

16.13.6 Example 3 - ComboBoxes

During the development of a program for measuring temperatures, a circuit board from Stephan Mischnik (www.strippenstrolch.de) could be used. It was only known that an NTC serves as a temperature sensor, a PIC 08M2+ was used as an AD converter and the temperature data could be read in via an RS232 interface. In order to keep the program test open, a combo box was used for the RS232 port and 5 combo boxes were used for setting the individual transmission parameters of the serial interface, whose ReadOnly property was set to True in each case:

CB2

Figure 16.13.6.1: Configuration RS232

Here only the use of the 6 ComboBoxes is of interest. Therefore, only selected passages from the source text are presented. The excerpts show how the lists of the combo boxes cmbSpeed, cmbParity, cmbDataBits, cmbStopBits and cmbFlow are filled statically - related to number and values. A special feature is that the list of the ComboBox cmbRs232PortName is only filled dynamically at runtime, depending on the serial interfaces found on the system or the USB-RS232 adapter interfaces:

[1] Public Sub Form_Open()
[2]   Dim aDataFlow As New String[]
[3][4]   aDataFlow.Add("None") 
[5]   aDataFlow.Add("XON/XOFF") 
[6]   aDataFlow.Add("RFR/CTS") 
[7]   aDataFlow.Add("RFR/CTS + XON/XOFF") 
[8]   cmbSpeed.List = ["2400", "4800", "9600"] 
[9]   cmbParity.Add("None") 
[10]   cmbParity.Add("Even") 
[11]   cmbParity.Add("Odd") 
[12]   cmbDataBits.List = ["5", "6", "7", "8"] 
[13]   cmbStopBits.List = ["1", "2"] 
[14]   cmbFlow.List = aDataFlow
[15]   
[16]   RS232PortListeGenerieren()
[17][18] End ' Form_Open
[19]  
[20] Public Sub RS232PortListeGenerieren() 
[21]   Dim iCount As Integer 
[22]   Dim sZeile, sListeV24, sListeUSB, s As String 
[23]   Dim aSchnittstellenMatrix As New String[] 
[24]   Dim aListe As New String[] 
[25]   Dim hProcess As Process 
[26]   
[27]   cmbRS232PortName.Clear() 
[28] 
[29] ' Ermittlung echter RS232-Schnittstellen 
[30]   Shell "dmesg | grep ttyS | grep 00:" To sListeV24 
[31]   If Len(sListeV24) > 0 Then 
[32]      aSchnittstellenMatrix = Split(sListeV24, " ") 
[33]      For Each sZeile In aSchnittstellenMatrix 
[34]          If InStr(sZeile, "ttyS") Then 
[35]             cmbRS232PortName.Add("/dev/" & Trim$(sZeile)) 
[36]          Endif 
[37]      Next ' FOR EACH 
[38]   Endif ' Len(sListeV24) > 0 ? 
[39] 
[40] ' Ermittlung USB-RS232-Adapter-Schnittstellen  
[41]   Shell "dmesg | grep ttyUSB" To sListeUSB 
[42]   If Len(sListeUSB) > 0 Then 
[43]      aSchnittstellenMatrix = Split(sListeUSB, "\n") 
[44]      For Each sZeile In aSchnittstellenMatrix 
[45]          For iCount = 0 To 7 
[46]              If InStr(sZeile, "ttyUSB" & CInt(iCount)) Then 
[47]                 aListe.Add("ttyUSB" & CInt(iCount)) 
[48]              Endif 
[49]          Next ' iCount 
[50]      Next ' FOR EACH 
[51]   Endif ' Len(sListeUSB) > 0 ? 
[52]   
[53]   aListe.Sort 
[54]   aListe = RemoveMultiple(aListe) 
[55] 
[56]   For iCount = 0 To aListe.Max 
[57]       cmbRS232PortName.Add("/dev/" & Trim$(aListe[iCount])) 
[58]   Next ' iCount 
[59] 
[60]   If cmbRS232PortName.Count = 0 
[61]      cmbRS232PortName.Background = Color.RGB(255, 191, 191) 
[62]      cmbRS232PortName.Add("           Keine RS232-Schnittstelle gefunden!") 
[63]      btnOnOff.Enabled = False 
[64]   Endif ' cmbRS232PortName.Count = 0 ?
[65] 
[66] End ' RS232PortListeGenerieren() 
[67] 
[68] Public Function RemoveMultiple(aStringListe As String[]) As String[] 
[69]   Dim iCount As Integer 
[70]   Dim iIndex As Integer 
[71]   Dim sElement As String 
[72] 
[73]   iIndex = 0 ' Initialisierung NICHT notwendig 
[74]   While iIndex < aStringListe.Count 
[75]     iCount = 0 
[76]     sElement = aStringListe[iIndex] 
[77]     While aStringListe.Find(sElement) <> -1 
[78]       Inc iCount 
[79]       aStringListe.Remove(aStringListe.Find(sElement)) 
[80]     Wend 
[81]     If iCount Mod 2 = 1 Then 
[82]        aStringListe.Add(sElement, iIndex) 
[83]        Inc iIndex 
[84]     Endif ' iCount Mod 2 = 1 ? 
[85]   Wend 
[86] 
[87]   Return aStringListe 
[88] 
[89] End ' RemoveMultiple(...)

After setting the correct transmission parameters, the expander could be folded in:

CB3

Figure 16.13.6.2: Temperature measurement

16.13.7 Example 4 - Editing ComboBox lists at runtime (export/import)

If you set the ReadOnly property of combo boxes to True, make sure that only valid data from these combo boxes is processed in the program. However, you can no longer change the lists directly in the combo box, which is sometimes necessary. The following project describes how to edit, export and import the lists of selected combo boxes at runtime.

CB4

Figure 16.13.7.1: Three combo boxes

CB5

Figure 16.13.7.2: Editing ComboBox lists (runtime)

Before closing the program window, the contents of the lists of the 3 combo boxes are stored in a separate file in the project directory (list export). Each time the main program is restarted, the contents of the three files are read out separately and assigned to the lists of the three combo boxes (list import).

The quite extensive but well-documented source code of the project is not specified here. It is definitely worthwhile to take a close look at the complete source code. The source code will offer you a lot of new features and will change your view on programming with gambas. This is mainly due to the fact that the source code for processing lists represents an excerpt from the source code of the Gambas IDE.

Download

The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k16/k16.13/start.txt · Last modified: 29.09.2023 by emma

Page Tools