Creating tabs

Tabs allow you to condense the information from several screens into a relatively small place. Tabs provide titles at the top of the window, which present an individual widget layout for each title when clicked. In this recipe, we'll create a simple tabbed interface.

Getting ready

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

How to do it...

We will create an overarching tab widget. Then, we'll create three generic widgets to represent our tabs. We'll set up layouts with three different GUI widgets and assign each layout to our tab widgets. Finally, we'll add our tabs to the tab widget and display it. To do this, we need to perform the following steps:

  1. First, we need to import the GUI and QGIS core libraries:
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    
  2. Next, we create our tab and configure its title and size:
    qtw = QTabWidget()
    qtw.setWindowTitle("PyQGIS Tab Example")
    qtw.resize(400,300)
    
  3. Now, we initialize our tab widgets:
    tab1 = QWidget()
    tab2 = QWidget()
    tab3 = QWidget()
    
  4. Then, we'll set up a widget and a layout with a rich text input box, using HTML tags for bold text for our first tab:
    layout1 = QVBoxLayout()
    layout1.addWidget(QTextEdit("<b>Type text here</b>"))
    tab1.setLayout(layout1)
    
  5. Now, we'll set up a simple button for our second tab, following the same format as the first tab:
    layout2 = QVBoxLayout()
    layout2.addWidget(QPushButton("Button"))
    tab2.setLayout(layout2)
    
  6. Next, we'll create the widget and the layout for our third tab with a simple text label:
    layout3 = QVBoxLayout()
    layout3.addWidget(QLabel("Label text example"))
    tab3.setLayout(layout3)
    
  7. Then, we'll add the tabs to the tab window:
    qtw.addTab(tab1, "First Tab")
    qtw.addTab(tab2, "Second Tab")
    qtw.addTab(tab3, "Third Tab")
    
  8. Finally, we'll display the tab window:
    qtw.show()
    
  9. Verify that you can click on each tab and interact with the widgets.

How it works...

The key to this recipe is the QTabWidget().method. Everything else is just arbitrary layouts and widgets, which are ultimately contained in the tab widget.

Note

The general rule of thumb for tabs is to keep the information in them independently.

There is no way to predict how the user will interact with a tabbed interface, and if the information across tabs is dependent, problems will arise.

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

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