【问题标题】:QLabel doesn't redraw correctly when in a QHBoxLayout with a stretch在带有拉伸的 QHBoxLayout 中时,QLabel 无法正确重绘
【发布时间】:2014-03-20 08:56:04
【问题描述】:

我遇到了一个奇怪的问题,即当文本更改时标签未正确重绘,当它位于 QHBoxLayout 内并增加了拉伸时。

考虑以下 (PyQt) 示例代码:

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

显示了两个小部件,一个带有 QHBoxLayout 并添加了拉伸,一个没有:

2 秒后,计时器将两个标签文本从“foo”设置为空字符串。在没有拉伸的小部件中,它按预期工作 - 但是,标签文本不会重绘:

那里发生了什么?这是一个Qt错误吗?我错过了什么吗?

到目前为止我发现了什么:

  • 这似乎只在设置空字符串时发生,设置较短的字符串可以正常工作。
  • 但是在我的实际应用程序中,它也没有添加拉伸。

我现在已将其提交为QTBUG-36945

【问题讨论】:

  • 这似乎是一个 Qt 错误。我能够为 PyQt5 和 C++ 客户端代码的 Qt 5.0.2 和 5.1.0 重现它。将.setText("") 替换为clear() 即可解决问题。尝试始终在setText 之前调用clear()。可能它会作为一个临时修复。这个问题需要进一步调查。我稍后会尝试这样做。
  • 我也试过了,虽然它解决了这个例子中的问题,但由于某种原因它对我的real code 没有帮助。但是在设置文本后执行repaint() 会有所帮助。
  • @PavelStrakhov 介意分享 C++ 代码,以便我可以将其附加到我报告的错误中吗?

标签: qt resize pyqt qwidget qlabel


【解决方案1】:

感谢#qt IRC 频道(在 Freenode 上)中的乐于助人的人,我想在设置文本后重新绘制解决问题:

class Label(QLabel):

    ...

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

我仍然很高兴知道我是否只是在某个地方弄错了,或者我是否应该提交一个 Qt 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多