Creating a combobox

A combobox provides a drop-down list to limit the user's selection to a defined set of choices. In this recipe, we'll create a simple combobox.

Getting ready

Open the QGIS Python Console by selecting the Plugins menu and then clicking on Python Console.

How to do it...

In this recipe, we will initialize the combobox widget, add choices to it, resize it, display it, and then capture the user input in a variable for printing to the console. To do this, we need to perform the following steps:

  1. Frist, we import the GUI library:
    from PyQt4.QtGui import *
    
  2. Now, we create our combobox object:
    cb = QComboBox()
    
  3. Next, we add the items that we want the user to choose from:
    cb.addItems(["North", "South", "West", "East"])
    
  4. Then, we resize the widget:
    cb.resize(200,35)
    
  5. Now we can display the widget to the user:
    cb.show()
    
  6. Next, we need to select an item from the list.
  7. Now, we set the user's choice to a variable:
    text = cb.currentText()
    
  8. Finally, we can print the selection:
    print text
    
  9. Verify that the selection is printed to the console.

How it works...

Items added to the combobox are a Python list. This feature makes it easy to dynamically generate choices using Python as the result of a database query or other dynamic data. You may also want the index of the object in the list, which you can access with the currentIndex property.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset