2

I'm having an odd problem with a label not being redrawn correctly when the text is changed, when it's inside a QHBoxLayout with an added stretch.

Consider the following (PyQt) example code:

from PyQt5.QtWidgets import QApplication, QHBoxLayout, QWidget, QLabel
from PyQt5.QtCore import QTimer

def clearlabel():
    print("clearing")
    lbl.setText("")
    lbl2.setText("")

app = QApplication([])

# Widget 1: with stretch

w = QWidget()
w.move(0, 0)
w.resize(100, 20)
w.show()

lbl = QLabel()
lbl.setText("foo")

h = QHBoxLayout(w)
h.addStretch()
h.addWidget(lbl)

# Widget 2: without stretch

w2 = QWidget()
w2.move(0, 40)
w2.resize(100, 20)
w2.show()

lbl2 = QLabel()
lbl2.setText("foo")

h2 = QHBoxLayout(w2)
h2.addWidget(lbl2)

QTimer.singleShot(1000, clearlabel)
app.exec_()

Two widgets are shown, one with a QHBoxLayout with a stretch added, one without:

widgets before changing string

After 2 seconds, a timer sets both label texts from "foo" to an empty string. In the widget without stretch it works like expected - with the one with, however, the label text doesn't get redrawn:

widgets after changing string

What's going on there? Is this a Qt bug? Am I missing something?

What I found out so far:

  • This only seems to happen when setting an empty string, setting a shorter string works fine.
  • However in my real application, it happens without a stretch added as well.

I have now submitted this as QTBUG-36945.

The Compiler
  • 11,126
  • 4
  • 40
  • 54
  • It seems like it's a Qt bug. I'm able to reproduce it for Qt 5.0.2 and 5.1.0 for both PyQt5 and C++ client code. Replacing `.setText("")` to `clear()` solves the problem. Try to always call `clear()` before `setText`. May be it will work as a temporary fix. This issue needs further investigation. I'll try to do that later. – Pavel Strakhov Feb 19 '14 at 21:10
  • I've tried that as well, and while it solves the issue in this example, it didn't help with my [real code](http://git.the-compiler.org/qutebrowser/tree/qutebrowser/widgets/statusbar.py) for some reason. However doing `repaint()` after setting the text helped. – The Compiler Feb 19 '14 at 21:14
  • @PavelStrakhov mind sharing the C++ code so I can attach it to the bug I've reported? – The Compiler Feb 20 '14 at 05:58

1 Answers1

1

Thanks to the helpful people in the #qt IRC channel (on Freenode), I figured out doing a repaint after setting the text works around the issue:

class Label(QLabel):

    ...

    def setText(self, text):
        super().setText(text)
        if not text:
             self.repaint()

Still I'd be glad to know if I'm just wrong somewhere, or if I should submit a Qt bug.

The Compiler
  • 11,126
  • 4
  • 40
  • 54