我想知道如何在QGraphicsPolygonItem
中添加文本?
在我的脚本中,我使用QPolygonF
和setPolygon
来绘制项目,我想知道您是否可以在其中插入文本?你知道吗
我做了一些研究,但我能发现的是有些人用QGraphicsTextItem
代替了多边形项,或者用QPainter
,我不知道如何与我的QPolygonF
结合。有人能告诉我怎么解决我的问题吗?你知道吗
编辑:
抱歉没有提供任何例子。下面是多边形项的示例-
from PySide2.QtGui import QColor, QPolygonF, QPen, QBrush
from PySide2.QtCore import Qt, QPointF, QPoint
from PySide2.QtWidgets import QDialog, QVBoxLayout, QGraphicsView, QGraphicsScene, QGraphicsPolygonItem, QApplication, \
QFrame, QSizePolicy
points_list = [[60.1, 19.6, 0.0], [60.1, 6.5, 0.0], [60.1, -6.5, 0.0], [60.1, -19.6, 0.0], [60.1, -19.6, 0.0],
[20.0, -19.6, 0.0], [-20, -19.6, 0.0], [-60.1, -19.6, 0.0], [-60.1, -19.6, 0.0], [-60.1, -6.5, 0.0],
[-60.1, 6.5, 0.0], [-60.1, 19.6, 0.0], [-60.1, 19.6, 0.0], [-20.0, 19.6, 0.0], [20.0, 19.6, 0.0],
[60.1, 19.6, 0.0]]
class MainWindow(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent=parent)
self.create()
def create(self, **kwargs):
main_layout = QVBoxLayout()
graphics = MainGraphicsWidget()
main_layout.addWidget(graphics)
self.setLayout(main_layout)
class MainGraphicsWidget(QGraphicsView):
def __init__(self, parent=None):
super(MainGraphicsWidget, self).__init__(parent)
self._scene = QGraphicsScene(backgroundBrush=Qt.gray)
self.setScene(self._scene)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setBackgroundBrush(QBrush(QColor(30, 30, 30)))
self.setFrameShape(QFrame.NoFrame)
self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
self.testButton = GraphicsButton()
self._scene.addItem(self.testButton)
class GraphicsButton(QGraphicsPolygonItem):
def __init__(self, parent=None):
super(GraphicsButton, self).__init__(parent)
self.myPolygon = QPolygonF([QPointF(v1, v2) for v1, v2, v3 in points_list])
self.setPen(QPen(QColor(0, 0, 0), 0, Qt.SolidLine, Qt.FlatCap, Qt.MiterJoin))
self.setPolygon(self.myPolygon)
self.setBrush(QColor(220, 40, 30))
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.setGeometry(500, 100, 500, 900)
window.show()
sys.exit(app.exec_())
所以这里应该是红方块一样的项目在中心,有人知道如何把一些文字里面?你知道吗
最简单的解决方案是添加一个QGraphicsSimpleTextItem,即图形项的子项。
对于矩形和regular polygons等简单形状,可以将项目放置在项目的中心。请记住,文本不会考虑父项形状,您必须以某种方式处理它;这意味着您必须考虑文本宽度和高度以及父项形状(对于不规则形状也是如此,但对于三角形和旋转正方形也是如此)。你知道吗
如您所见,结果超出父边界:
一种可能的替代方法是使用QGraphicsTextItem并设置其textWidth:
请注意,与QGraphicsSimpleTextItem(使用默认的黑色进行绘制)相反,QGraphicsTextItem使用小部件的当前调色板WindowTextrole,该调色板WindowTextrole继承自应用程序、视图,或继承自之前设置了它的任何视图父级(一旦设置了默认文本颜色,即使调色板已更改,也不会更改)。你知道吗
相关问题 更多 >
编程相关推荐