pyqt qtabwidget horizontal tab and horizontal text in QtDesigner
Asked Answered
F

4

2

enter image description herei am having problem to change text alignment using pyqt4 desginer i have made tabs horizontal by aligning west but the text in that goes north to south that looks bad i want to change alignment of text as horizontal how can i do that...thanks in advance.

this is my ui.py code

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.tabWidget = QtGui.QTabWidget(self.centralwidget)
        self.tabWidget.setTabPosition(QtGui.QTabWidget.West)
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
        self.tab = QtGui.QWidget()
        self.tab.setObjectName(_fromUtf8("tab"))
        self.tabWidget.addTab(self.tab, _fromUtf8(""))
        self.tab_2 = QtGui.QWidget()
        self.tab_2.setObjectName(_fromUtf8("tab_2"))
        self.tabWidget.addTab(self.tab_2, _fromUtf8(""))
        self.tab_3 = QtGui.QWidget()
        self.tab_3.setObjectName(_fromUtf8("tab_3"))
        self.tabWidget.addTab(self.tab_3, _fromUtf8(""))
        self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 31))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Page", None))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

and this is my main file where i ll add all the functions and from here i generate my window

from untitled import *
from PyQt4 import QtGui # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication
import os

from PyQt4.QtGui import *
from PyQt4.QtCore import *


class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
Frizette answered 6/10, 2017 at 13:49 Comment(8)
You can show an image of what you get and what you want to get. :PWaki
@Waki m getting this as displayed and i want the text in the tabs to be horizontal tooFrizette
@ekhumoro do you even see painter explained in that question that guy already has implemented text just had a problem with painter syntax and here the start is a sratchFrizette
@CodingHub. The other answer has a fully working example. I tried it, and it works perfectly. All you need is the FingerTabWidget class. In your code, you can just do self.tabWidget.setTabBar(FingerTabWidget(width=100,height=25)). (Adjust the width and height as you please).Penguin
@Penguin it makes the tabs invisible and i have updated the code as you saidFrizette
@Penguin and how can i add tabs again here ? without changing my untitled.py?Frizette
@CodingHub. After some more testing, I think there are some issues with the FingerTabWidget class. The original example works well, but it seems to break too easily in other contexts. So I am going to re-open this question.Penguin
@Penguin yes now there is no way that without editing ui file(that must not be edited) you can't get the data back as you need to use that line of code after the line where we declare the tabwidget and also icons are lost afterwordsFrizette
W
3

The solution that I propose may not be the exact solution but I think it is the one that comes closest. What I propose is to promote the QTabWidget to use a custom QTabWidget.

Before that I have improved the solution proposed in this answer:

tabwidget.py

from PyQt4 import QtGui, QtCore


class HorizontalTabBar(QtGui.QTabBar):
    def paintEvent(self, event):
        painter = QtGui.QStylePainter(self)
        option = QtGui.QStyleOptionTab()
        for index in range(self.count()):
            self.initStyleOption(option, index)
            painter.drawControl(QtGui.QStyle.CE_TabBarTabShape, option)
            painter.drawText(self.tabRect(index),
                             QtCore.Qt.AlignCenter | QtCore.Qt.TextDontClip,
                             self.tabText(index))

    def tabSizeHint(self, index):
        size = QtGui.QTabBar.tabSizeHint(self, index)
        if size.width() < size.height():
            size.transpose()
        return size


class TabWidget(QtGui.QTabWidget):
    def __init__(self, parent=None):
        QtGui.QTabWidget.__init__(self, parent)
        self.setTabBar(HorizontalTabBar())

This file will be stored next to the .ui file and the .py files as shown in the following structure:

.
├── main.py        # file of class MainWindow(QMainWindow,Ui_MainWindow):
├── tabwidget.py   # custom QTabWidget
├── untitled.py    
└── untitled.ui    # your design

After having the previous structure we open the .ui file with Qt Designer and we right click on the QTabWidget and select promoted to ...:

enter image description here

A dialogue will open and the following should be placed in it:

enter image description here

Then press the add button and then the promote button, and at the end you generate the .py file again with the help of pyuic

At the end you get the following widget:

enter image description here

Waki answered 7/10, 2017 at 3:36 Comment(6)
you have any idea how can i add icons to them as they removed now?Frizette
and how can i change the of tabs by giving them custom size of my ownFrizette
@SahilJain. This is essentially the same solution that I originally gave you, so it still has the same limitations.Penguin
@Penguin The solution of how to build the widget is the same, my answer is mainly oriented to guide you if you want to apply in Qt Designer should do so by promoting the widget.Waki
@eyllanesc. It wasn't a criticism of your answer - I was just pointing out that the code from the other answer is not a complete solution. This is why I decided to re-open the question. Getting the existing tab-bar class to work with the OPs example won't solve all the problems (e.g. rendering icons).Penguin
no, just clarified my answer. As I have observed the source code of QTabBar.h it creates the close button in the private method when using the initStyleOption method, so I think that modifying some existing code will not be the solution for the icon. The most convenient thing I think is to create override methods but not invoke the parent and take care of painting the icon in paintEvent. This generates that the use qss is not recommendable. :PWaki
Y
1

I know this has been awhile but if anyone needs @Sahil Jain's answer in PyQt5 version, please refer to following for your tabwidget.py

from PyQt5 import QtGui, QtCore, QtWidgets


class HorizontalTabBar(QtWidgets.QTabBar):
    def paintEvent(self, event):

        painter = QtWidgets.QStylePainter(self)
        option = QtWidgets.QStyleOptionTab()
        for index in range(self.count()):
            self.initStyleOption(option, index)
            painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, option)
            painter.drawText(self.tabRect(index),
                             QtCore.Qt.AlignCenter | QtCore.Qt.TextDontClip,
                             self.tabText(index))

    def tabSizeHint(self, index):
        size = QtWidgets.QTabBar.tabSizeHint(self, index)
        if size.width() < size.height():
            size.transpose()
        return size


class TabWidget(QtWidgets.QTabWidget):
    def __init__(self, parent=None):
        QtWidgets.QTabWidget.__init__(self, parent)
        self.setTabBar(HorizontalTabBar())
Yolondayon answered 31/7, 2020 at 20:48 Comment(0)
F
0

Using the above method and after that adding a line of code to it and got my icons displayed

from PyQt4 import QtGui, QtCore


class HorizontalTabBar(QtGui.QTabBar):
    def paintEvent(self, event):
        painter = QtGui.QStylePainter(self)
        option = QtGui.QStyleOptionTab()
        for index in range(self.count()):
            self.initStyleOption(option, index)
            painter.drawControl(QtGui.QStyle.CE_TabBarTabShape, option)
            painter.drawText(self.tabRect(index),
                             QtCore.Qt.AlignCenter | QtCore.Qt.TextDontClip,
                             self.tabText(index))
            if index == 0:
                painter.drawImage(QtCore.QRectF(10, 10, 66, 67), QtGui.QImage("ico/HOME.png"))

    def tabSizeHint(self, index):
        size = QtGui.QTabBar.tabSizeHint(self, index)
        size.setHeight=50
        size.setWidth=200
        if size.width() < size.height():
            size.transpose()
        return size


class TabWidget(QtGui.QTabWidget):
    def __init__(self, parent=None):
        QtGui.QTabWidget.__init__(self, parent)
        self.setTabBar(HorizontalTabBar())

you can add icons as per the indexes of your tabs and set their position accordingly till now this is best solution i can give.cheers

Frizette answered 12/10, 2017 at 19:41 Comment(0)
K
0

Better way for looks and usability:

At the Qt Designer>

  1. Use QToolBox at left side and QTabWidget at right.
  2. Connect both with signal (currentChanged(int) - setCurrentIndex(int)).
  3. Hide QTabWidget header with following css.

QTabBar::tab {height: 0px;}

Here an Example:

QToolBox with QTabWidget

Kacey answered 12/7, 2020 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.