Seth Koberg
Seth Koberg

Reputation: 1055

PyQt4 menu acction to add new tab to QTabWidget

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

Upvotes: 3

Views: 3112

Answers (2)

ekhumoro
ekhumoro

Reputation: 120608

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_())

Upvotes: 4

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

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

Upvotes: 0

Related Questions