【发布时间】: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()
【问题讨论】: