Place the text in the middle of QProgressBar when setRange(0, 0) on Windows?

6.1k views Asked by At

How to place text (not just a number) in the middle of QProgressBar when setRange(0, 0) on Windows?

The following is a PyQt example which still doesn't work as expected.

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

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(800, 600)

#        self.lb=QLabel('finding resource   ')

        self.pb = QProgressBar()
        self.pb.setRange(0, 0)

        self.pb.setAlignment(Qt.AlignCenter)
        self.pb.setFormat('finding resource...')
        self.pb.setStyleSheet("text-align: center;")

#        self.pb.setTextVisible(False)


        self.statusBar().setSizeGripEnabled(False)
#        print(self.statusBar().layout() )
        self.statusBar().setStyleSheet("QStatusBar::item {border: none;}")
        self.statusBar().addPermanentWidget(self.pb, 1)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    ui = MainWindow()
    ui.show()
    sys.exit(app.exec_())
2

There are 2 answers

6
NoDataDumpNoContribution On BEST ANSWER

vahancho explained the reason nicely in his answer and mentioned to override QProgressBar.text(). Fortunately this is straightforward in Python and I know how to do it.

from PySide import QtGui, QtCore

class MyProgressBar(QtGui.QProgressBar):
"""
    Progress bar in busy mode with text displayed at the center.
"""

    def __init__(self):
        super().__init__()
        self.setRange(0, 0)
        self.setAlignment(QtCore.Qt.AlignCenter)
        self._text = None

    def setText(self, text):
        self._text = text

    def text(self):
        return self._text

app = QtGui.QApplication([])

p = MyProgressBar()
p.setText('finding resource...')
p.show()

app.exec_()

gives

enter image description here

This is on Windows 7.

Btw. First I thought about the brute force approach: QStackedLayout with a QLabel on top of a QProgressBar. That should also always work.

4
vahancho On

The reason of why you do not see a text in your progress bar when the range is set to min=0 and max=0, is that QProgressBar::text() function returns an empty string in that case. The source code of QProgressBar::text() function contains the following lines:

QString QProgressBar::text() const
{
    Q_D(const QProgressBar);
    if ((d->maximum == 0 && d->minimum == 0) || d->value < d->minimum
            || (d->value == INT_MIN && d->minimum == INT_MIN))
        return QString(); // <---- an empty string on null range.
[..]

Therefor the text is invisible. The only way you can change the behavior is overriding the QProgressBar::text() function as it is declared to be a virtual function. Unfortunately I do not know how to do it in Python.