我是 Python 的新手。我用固定坐标绘制了多边形和圆。现在我想用鼠标将这个多边形和圆移动到窗口上的其他地方。请指导我该怎么做?
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyFrame(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self)
def paintEvent(self, event=None):
paint=QPainter(self)
paint.setPen(QPen(QColor(Qt.green).dark(150),1,Qt.SolidLine))
segColor=QColor(Qt.green).dark(150)
paint.setBrush(segColor)
paint.setBrushOrigin(QPoint(225,225))
polygon=QPolygon([QPoint(250,175), QPoint(265,175), QPoint(250,190), QPoint(265,190),QPoint(250,175)])
paint.drawPolygon(polygon)
paint.setPen(QPen(QColor(Qt.red),1,Qt.SolidLine))
paint.setBrush(QBrush(Qt.NoBrush))
polygon1=QPolygon([QPoint(250,300), QPoint(250,500), QPoint(350,500), QPoint(350,300)])
paint.drawPolyline(polygon1)
paint.drawEllipse(50,50,50,50)
app=QApplication(sys.argv)
f=MyFrame()
f.show()
app.exec_()
最佳答案
您应该查看 QGraphicsView 而不是您在做什么,它已经内置了所有内容。
http://doc.qt.nokia.com/4.7-snapshot/qgraphicsview.html
http://doc.qt.nokia.com/4.7-snapshot/qgraphicsscene.html
from PyQt4 import QtGui, QtCore
class MyFrame(QtGui.QGraphicsView):
def __init__( self, parent = None ):
super(MyFrame, self).__init__(parent)
self.setScene(QtGui.QGraphicsScene())
# add some items
x = 0
y = 0
w = 45
h = 45
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
brush = QtGui.QBrush(pen.color().darker(150))
item = self.scene().addEllipse(x, y, w, h, pen, brush)
item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
if ( __name__ == '__main__' ):
app = QtGui.QApplication([])
f = MyFrame()
f.show()
app.exec_()
编辑:展示如何创建 QPainterPath
from PyQt4 import QtGui, QtCore
class MyFrame(QtGui.QGraphicsView):
def __init__( self, parent = None ):
super(MyFrame, self).__init__(parent)
scene = QtGui.QGraphicsScene()
self.setScene(scene)
# add some items
x = 0
y = 0
w = 45
h = 45
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
brush = QtGui.QBrush(pen.color().darker(150))
item = scene.addEllipse(x, y, w, h, pen, brush)
item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
# create an open path
path = QtGui.QPainterPath()
path.moveTo(-w, -h)
path.lineTo(-w, h)
path.lineTo(w, h)
path.lineTo(w, -h)
clr = QtGui.QColor('blue')
clr.setAlpha(120)
brush = QtGui.QBrush(clr)
pen = QtGui.QPen(QtCore.Qt.NoPen)
fill_item = scene.addRect(-w, y, w*2, h, pen, brush)
path_item = scene.addPath(path)
if ( __name__ == '__main__' ):
app = QtGui.QApplication([])
f = MyFrame()
f.show()
app.exec_()
关于Python PyQt : How can I move my widgets on the window with mouse?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12213391/