phimath
phimath

Reputation: 1422

Force Qt/PyQt/PySide QTabWidget to resize to active tab

I have a QTabWidget working correctly except that it doesn't re-size how I would expect it.

There are 2 tabs in the widget. Each has a QVBoxLayout with widgets in it. The VBox also works as expected.

The issue is that the first tab has more widgets in its layout than the second tab. When viewing the first tab, the tab sizes to appropriately contain the widgets inside of it. However, when viewing the second tab, the tab widget stays the same size of the first, instead of re-sizing to the visible widgets.

Is this behavior expected? If so, what is a good work around? Id like for the tab widget to always scale to the currently active widget.

EDIT: Here is an example of the issue. The desired behavior is for Tab B to shrink to its proper size, which can be seen by commenting out the line noted below.

#!/bin/python
import sys
from PySide import QtGui, QtCore

class TabExample(QtGui.QWidget):
    def __init__(self):
        super(TabExample, self).__init__()
        self.initUI()

    def initUI(self):
        self.vbox_main = QtGui.QVBoxLayout()

        self.table_blank = QtGui.QTableWidget(10, 4)

        self.tabw = QtGui.QTabWidget()
        self.tab_A = QtGui.QWidget()
        self.vbox_A = QtGui.QVBoxLayout(self.tab_A)

        for i in range(20):
            lab = QtGui.QLabel('label %d' %i)
            self.vbox_A.addWidget(lab)

        self.tab_B = QtGui.QWidget()
        self.vbox_B = QtGui.QVBoxLayout(self.tab_B)

        for i in range(5):
            lab = QtGui.QLabel('labelB %d'%i)
            self.vbox_B.addWidget(lab)

        #COMMENT OUT NEXT LINE TO SEE DESIRED SIZE OF TAB B
        self.tabw.addTab(self.tab_A, 'Tab A')

        self.tabw.addTab(self.tab_B, 'Tab B')

        self.vbox_main.addWidget(self.table_blank, 1)
        self.vbox_main.addWidget(self.tabw)

        self.setLayout(self.vbox_main)
        self.setGeometry(0,0, 400, 600)
        self.move(QtGui.QDesktopWidget().availableGeometry().center() - self.frameGeometry().center())
        self.show()


def main():
    app = QtGui.QApplication(sys.argv)
    tabExample = TabExample()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

Upvotes: 1

Views: 2679

Answers (1)

kblst
kblst

Reputation: 519

This should do the trick; change the size policy depending on which tab is active.

def __init__(self):
    super(Widget, self).__init__()
    self.setupUi(self)
    self.tabWidget_2.currentChanged.connect(self.updateSizes)

def updateSizes(self):
    for i in range(self.tabWidget_2.count()):
        self.tabWidget_2.widget(i).setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

    current = self.tabWidget_2.currentWidget()
    current.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

Upvotes: 0

Related Questions