如何在QGraphicsRectItem上居中对齐QGraphicsTextItem?
QGraphicsTextItem 无法居中对齐 QGraphicsRectItem 的问题
我正尝试将QGraphicsTextItem居中放置在QGraphicsRectItem上。已经设置了SceneRect,认为所有元素都应映射到[0,0](参考其他帖子的建议),但不清楚为何使用setPos()无法让文本元素与矩形对齐。
如图所示,尽管文本应位于单元中心,但它在水平和垂直轴上都有明显偏移:
以下是带有所有元素边框的代码示例:
import sys from PyQt6.QtCore import * from PyQt6.QtGui import * from PyQt6.QtWidgets import * class MainWindow(QMainWindow): def __init__(self, *args, parent=None): super().__init__(*args, parent=parent) self.setWindowTitle("Timeline") self.resize(1000,500) self.toolbar=QToolBar() self.toolbar.addAction("New Event") self.addToolBar(self.toolbar) self.drawScene=QGraphicsScene() self.drawView=QGraphicsView() self.drawView.setScene(self.drawScene) self.setCentralWidget(self.drawView) self.drawScene.setSceneRect(0,0,self.window().width(),self.window().height()) unit_len=200 winH=self.window().height() winW=self.window().width() padX=30 padY=30 self.drawView.setAlignment(Qt.AlignmentFlag.AlignCenter) unitPen=QPen(Qt.GlobalColor.green) unitPen.setWidth(0) unitBrush=QBrush(Qt.GlobalColor.lightGray) units=[2001,2002,2003,2004,2005] dist=0 for i in units: r=QRectF(QPointF(padX+dist,(winH/2)-20),QPointF(padX+dist+unit_len,(winH/2)+20)) self.drawScene.addRect(r,unitPen, unitBrush) r=QLineF(QPointF(padX+dist,(winH/2)),QPointF(padX+dist+unit_len,(winH/2))) self.drawScene.addLine(r,QPen(Qt.GlobalColor.red)) t=self.drawScene.addText(str(i)) t.setPos(QPointF(padX+dist+(unit_len/2), (winH/2)-(t.boundingRect().height()/2))) t.setDefaultTextColor(Qt.GlobalColor.blue) t.setFont(QFont("Segoe UI",12,700)) self.drawScene.addRect(t.sceneBoundingRect(),QPen(Qt.GlobalColor.red)) dist+=unit_len self.drawScene.addRect(QRectF(QPointF(padX+dist,(winH/2)-20),QPointF(padX+dist+padX,(winH/2)+20)), QPen(Qt.GlobalColor.white), QBrush(Qt.GlobalColor.white)) app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
内容的提问来源于stack exchange,提问作者rllysleepy
相关产品推荐
相关产品推荐

