You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 19:33:08