QListWidget为空时如何设置占位符文本居中?
Posted
技术标签:
【中文标题】QListWidget为空时如何设置占位符文本居中?【英文标题】:How to set the placeholder text in the center when the QListWidget is empty? 【发布时间】:2020-02-05 12:56:00 【问题描述】:PySide2/PyQt QListWidget为空时如何设置居中占位文字?
当 QListWidget 的项目为零时,我想在 QListWidget 的中心设置提示文本。
谢谢!
【问题讨论】:
请提供minimal reproducible example 【参考方案1】:如果项目数为零,则必须重写 paintEvent 方法并绘制文本:
from PyQt5 import QtCore, QtGui, QtWidgets
class ListWidget(QtWidgets.QListWidget):
def __init__(self, parent=None):
super().__init__(parent)
self._placeholder_text = ""
@property
def placeholder_text(self):
return self._placeholder_text
@placeholder_text.setter
def placeholder_text(self, text):
self._placeholder_text = text
self.update()
def paintEvent(self, event):
super().paintEvent(event)
if self.count() == 0:
painter = QtGui.QPainter(self.viewport())
painter.save()
col = self.palette().placeholderText().color()
painter.setPen(col)
fm = self.fontMetrics()
elided_text = fm.elidedText(
self.placeholder_text, QtCore.Qt.ElideRight, self.viewport().width()
)
painter.drawText(self.viewport().rect(), QtCore.Qt.AlignCenter, elided_text)
painter.restore()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = ListWidget()
w.placeholder_text = "Stack Overflow"
w.show()
# test
def on_timeout():
import random
if w.count() > 0:
w.clear()
else:
w.addItems(["item-".format(i) for i in range(random.randint(5, 10))])
timer = QtCore.QTimer(interval=1000, timeout=on_timeout)
timer.start()
sys.exit(app.exec_())
【讨论】:
以上是关于QListWidget为空时如何设置占位符文本居中?的主要内容,如果未能解决你的问题,请参考以下文章