Search code examples
pythonqtpyqt4qtabwidgetqtabbar

QTabBar neither expands totally nor spaces tabs equally


I want the tabbar to expand over the empty space until the right. And best would be if all tabs had the same width. I don't know how to do that as my stylesheets don't work and I can't find an option in the docs.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtGui,QtCore
import sys

class Main(QWidget):
    def __init__(self,parent=None):
        QWidget.__init__(self)
        self.setFixedSize(600,500)

        self.tabBar=QTabBar(self)
        self.tabBar.setStyleSheet("QTabBar{width:400px;}")
        self.tabBar.setExpanding(True)

        self.layout=QVBoxLayout(self)
        self.layout.addWidget(self.tabBar)

        self.tabBar.addTab("Kontext Menu")
        self.tabBar.addTab("Settings in detail")
        self.tabBar.addTab("Help and tips")
        self.tabBar.addTab("About")
        self.tabBar.addTab("Credits")

        self.show()

if __name__ == '__main__':
    app=QApplication(sys.argv)
    sd=Main()
    app.exec()

enter image description here

I have the idea, as the dialog shall have fixed size, that one can calculate eachs tab width as Totalwidth/(Amount of Tabs), but still I don't know how to tell each tab its width...


Solution

  • You can expand the tabs by using void setExpanding(bool enabled). See the documentation for details:

    http://qt-project.org/doc/qt-5.1/qtwidgets/qtabbar.html#expanding-prop

    Also, you will need to use the proper style syntax because you seem to lack the proper scope, i.e. the "::tab" part.

    Also, you would need to set the style sheet on the QTabWidget itself as opposed to QTabBar. It may be a bit weird at first, but that is the correct way of achieving what you wish to have.

    Here you can find the the code you should write:

    from PyQt4.QtGui import *
    from PyQt4.QtCore import *
    from PyQt4 import QtGui,QtCore
    import sys
    
    class Main(QWidget):
        def __init__(self,parent=None):
            QWidget.__init__(self)
            self.setFixedSize(600,500)
    
            self.tabBar=QTabBar(self)
            self.tabBar.setStyleSheet("QTabBar::tab{width:400px;}")
            self.tabBar.setExpanding(True)
    
            self.layout=QVBoxLayout(self)
            self.layout.addWidget(self.tabBar)
    
            self.tabBar.addTab("Kontext Menu")
            self.tabBar.addTab("Settings in detail")
            self.tabBar.addTab("Help and tips")
            self.tabBar.addTab("About")
            self.tabBar.addTab("Credits")
    
            self.show()
    
    if __name__ == '__main__':
        app=QApplication(sys.argv)
        sd=Main()
        app.exec()