3

我想使用 PyQt 在 Python 脚本中通过鼠标单击绘制一条由多个点组成的线。我需要所有的 ponts 坐标,我希望能够删除这条线。这是我的脚本完成所有工作,除了图形线条图本身,它只是打印它所做的事情:

#!/usr/bin/python3

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

class endomess(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.draw = False

    def mousePressEvent(self, event):

        if event.button() == Qt.LeftButton:

            if self.draw == False:
                print('Starting to draw at', str(event.pos()))
                self.draw = True
                self.linePoints = []

            elif self.draw == True:
                print('Appending', str(event.pos()))

            self.linePoints.append(event.pos())

        elif event.button() == Qt.RightButton:
            if self.draw == True:
                print('Finished drawing. List of all points:', str(self.linePoints))
                self.draw = False

def main(argv):
    app = QApplication(argv, True)
    wnd = endomess()
    wnd.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main(sys.argv)

所以,这是我的问题:我如何实际绘制可以通过上述脚本定义的线?我已经看过 scribble.py 和一些 Qt 绘画文档,但我不明白。对于 Qt 经验丰富的人来说,这可能不是问题吗?

提前感谢所有帮助!

4

1 回答 1

11

您可能应该使用图形视图框架来绘制线条,而不是尝试直接绘制它们。

这是一个让您入门的基本演示:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.view = View(self)
        self.button = QtGui.QPushButton('Clear View', self)
        self.button.clicked.connect(self.handleClearView)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.view)
        layout.addWidget(self.button)

    def handleClearView(self):
        self.view.scene().clear()

class View(QtGui.QGraphicsView):
    def __init__(self, parent):
        QtGui.QGraphicsView.__init__(self, parent)
        self.setScene(QtGui.QGraphicsScene(self))
        self.setSceneRect(QtCore.QRectF(self.viewport().rect()))

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

    def mouseReleaseEvent(self, event):
        start = QtCore.QPointF(self.mapToScene(self._start))
        end = QtCore.QPointF(self.mapToScene(event.pos()))
        self.scene().addItem(
            QtGui.QGraphicsLineItem(QtCore.QLineF(start, end)))
        for point in (start, end):
            text = self.scene().addSimpleText(
                '(%d, %d)' % (point.x(), point.y()))
            text.setBrush(QtCore.Qt.red)
            text.setPos(point)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())
于 2012-11-13T22:49:57.457 回答