2

I'm working on a small application for work w/ python and PyQt4 for the GUI. What I'm trying to accomplish is having a tabbed GUI where when a user clicks on a menu item, the action taken adds a tab to the QTabWidget. I'm currently having trouble getting an action to do such a thing. I've tried creating the GUI by hand and with QT designer, but I cant figure out how, if at all possible, to get an action to add a tab to the QTabWidget. This is my python code:

import sys
from PyQt4 import QtGui, uic

class TestGUI(QtGui.QMainWindow):
    def __init__(self):
        super(TestGUI, self).__init__()
        uic.loadUi('TEST.ui', self)
        self.show()

        self.actionAdd_Tab.triggered.connect(addTab)

def addTab():
    print 'This works'
    #Add new tab to GUI

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = TestGUI()
    sys.exit(app.exec_())

Pressing the menu item prints 'This works' to the console, so I know that its calling the addTab() function, but how do I get it to add a Tab?

Let me know if you would like to see the .ui file if it will help

Seth Koberg
  • 965
  • 2
  • 9
  • 15

2 Answers2

3

The handler for your action needs to create a tab label, and also a widget for the contents of the tab, so that they can be added to the tabwidget.

As a start, try something like this:

import sys
from PyQt4 import QtGui, uic

class TestGUI(QtGui.QMainWindow):
    def __init__(self):
        super(TestGUI, self).__init__()
        uic.loadUi('TEST.ui', self)
        self.actionAdd_Tab.triggered.connect(self.handleAddTab)

    def handleAddTab(self):
        contents = QtGui.QWidget(self.tabWidget)
        layout = QtGui.QVBoxLayout(contents)
        # add other widgets to the contents layout here
        # i.e. layout.addWidget(widget), etc
        self.tabWidget.addTab(contents, 'Tab One')

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = TestGUI()
    window.show()
    sys.exit(app.exec_())
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
0

QTabWidget's addTab() method, coincidentally named the same, adds a tab.

Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44
  • I've tried using this in the function to add the new tab, but I get 'NameError: global name 'tabWidget' is not defined' – Seth Koberg Nov 08 '13 at 16:53
  • @SethKoberg You need to put it in the class with a self argument and then use `self.tabWidget` to refer to the QTabWidget (assuming you have named it so in the UI). Basically like ekhumoro's solution. – Ramchandra Apte Nov 09 '13 at 03:51