使用PyQt绘制由多个点组成的线

时间:2012-11-13 21:16:42

标签: python pyqt drawing pyqt4

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

#!/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更有经验的人来说,这不是问题吗?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:10)

您应该使用graphics view framework绘制线条,而不是尝试直接绘制线条。

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

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_())