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

◇◆丶佛笑我妖孽 提交于 2020-03-03 10:13:08

问题


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

回答1:


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)


来源:https://stackoverflow.com/questions/28710003/force-qt-pyqt-pyside-qtabwidget-to-resize-to-active-tab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!