【问题标题】:Qt Line drawing to unexpected locationQt线条绘制到意外位置
【发布时间】:2011-11-19 01:41:35
【问题描述】:

我正在尝试编写一个绘图程序,但我在绘制线条时遇到了问题。当我在QGraphicsView 的底部画一条线时,这条线被绘制到小部件的中心。为什么?我认为我对 mapTo 函数的理解不够好,但是我阅读 Qt 文档的次数越多,我就越感到困惑。希望有人能帮忙。

from PyQt4.QtGui  import *
from PyQt4.QtCore import *

import sys

class Main(QWidget):

    def __init__(self, parent):
        super(Main, self).__init__(parent)

        self.resize(300, 300)
        vBox = QVBoxLayout(self)
        view = View(self)
        vBox.addWidget(view)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            sys.exit()

class View(QGraphicsView):

    def __init__(self, parent):
        super(View, self).__init__(parent)
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)

    def mousePressEvent(self, event):
        self.start = event.pos()

    def mouseReleaseEvent(self, event):
        self.stop = event.pos()
        self.line = Line(self, self.start, self.stop)
        self.scene.addItem(self.line)

class Line(QGraphicsLineItem):

    def __init__(self, parent, *args):
        # args = start, stop
        points = map(parent.mapToScene, args)
        (start, stop) = map(QPointF, points)

        self.line = QLineF(start, stop)
        super(Line, self).__init__(self.line)        

def run():
    app = QApplication(sys.argv)
    a   = Main(None)
    a.show()
    sys.exit(app.exec_())

run()

【问题讨论】:

    标签: qt qt4 pyqt pyqt4


    【解决方案1】:

    如果您没有为场景设置矩形,则会自动计算一个矩形,并且视图将以其中的对象为中心。

    要解决此问题,请将以下内容添加到 View.__init__() 的末尾:

    self.setSceneRect(QRectF(self.viewport().rect()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多