Pyqtgraph TextItem 居中对齐文本
Pyqtgraph TextItem center align text
我正在尝试使用 pyqtgraph 使文本居中对齐,而不是使用 html 左对齐。但是,当我使用 <div style="text-align: center"></div>
时似乎没有效果。
import sys
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets
app = QtWidgets.QApplication(sys.argv)
win = QtWidgets.QMainWindow()
gv = pg.GraphicsView()
win.setCentralWidget(gv)
win.show()
text = pg.TextItem(html='<div style="text-align: center">I am on the top<br>bottom</div>',
fill=QtGui.QColor(255, 255, 255))
text.setPos(100, 100)
gv.addItem(text)
sys.exit(app.exec_())
给予
底部文本根本没有居中对齐,例如当我将 <div style="text-align: center"></div>
更改为 <div style="text-align: right"></div>
时,它仍然没有任何作用。我做错了什么?
如果你想设置文本对齐方式你可以使用内部QGraphicsTextItem的document():
text = pg.TextItem(html='<div>I am on the top<br>bottom</div>',
fill=QtGui.QColor(255, 255, 255))
it = text.textItem
option = it.document().defaultTextOption()
option.setAlignment(QtCore.Qt.AlignCenter)
it.document().setDefaultTextOption(option)
it.setTextWidth(it.boundingRect().width())
text.setPos(100, 100)
gv.addItem(text)
我正在尝试使用 pyqtgraph 使文本居中对齐,而不是使用 html 左对齐。但是,当我使用 <div style="text-align: center"></div>
时似乎没有效果。
import sys
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets
app = QtWidgets.QApplication(sys.argv)
win = QtWidgets.QMainWindow()
gv = pg.GraphicsView()
win.setCentralWidget(gv)
win.show()
text = pg.TextItem(html='<div style="text-align: center">I am on the top<br>bottom</div>',
fill=QtGui.QColor(255, 255, 255))
text.setPos(100, 100)
gv.addItem(text)
sys.exit(app.exec_())
给予
底部文本根本没有居中对齐,例如当我将 <div style="text-align: center"></div>
更改为 <div style="text-align: right"></div>
时,它仍然没有任何作用。我做错了什么?
如果你想设置文本对齐方式你可以使用内部QGraphicsTextItem的document():
text = pg.TextItem(html='<div>I am on the top<br>bottom</div>',
fill=QtGui.QColor(255, 255, 255))
it = text.textItem
option = it.document().defaultTextOption()
option.setAlignment(QtCore.Qt.AlignCenter)
it.document().setDefaultTextOption(option)
it.setTextWidth(it.boundingRect().width())
text.setPos(100, 100)
gv.addItem(text)