2012-08-31 7 views
3

저는 파이썬을 처음 사용합니다. 고정 좌표계로 폴리곤과 원을 그렸습니다. 이제이 다각형과 원을 마우스를 사용하여 창상의 다른 위치로 이동하고 싶습니다. 내가 어떻게 할 수 있는지 안내해 주시겠습니까?Python PyQt : 마우스로 위젯을 창에서 어떻게 움직일 수 있습니까?

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

답변

8

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

귀한 답장을 보내 주신 Eric에게 감사의 말씀을 전합니다. 그러나 이로 인해 부분적으로 문제가 해결되었습니다. 실제로 저는 폴리 라인을 사용하여 그려지는 물 탱크를 그려야합니다. 왜냐하면 저는 3면이 필요하고 꼭지가 필요하지 않기 때문입니다. 그리고 'QGraphicsScene'객체에는 'addPolyline'속성이 없습니다. 둘째, 저는 제 가치에 따라 탱크를 채우고 싶습니다. 물 탱크를 채우려면 어떻게해야합니까 (파란색으로 볼 수 있습니까)? – mrtak

+0

장면의 오브젝트를 제어 할 수 있습니다. 단순한 모양 오브젝트 일 필요는 없습니다. 필자는 작성을 지원하는 QPainterPath를 정의 할 수있는 QGraphicsPathItem을 살펴 보는 것으로 시작합니다. 그보다 복잡한 항목의 경우, 닫히고 자신 만의 paintEvent 메소드를 구현하는 모든 QGraphicsItem을 서브 클래스화할 수 있습니다. –

+0

경로를 추가하는 바로 가기가 QGraphicsScene.addPath입니다. –

0

를 만드는 방법을 표시, 여기에 자사의 X를 업데이트하여 점을 애니메이션 몇 가지 코드입니다 및 y 좌표.


from PyQt5.QtGui import QPen, QBrush, QColor 
from PyQt5.QtCore import Qt, QTimer 
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QGraphicsItem, QApplication 

class GameWindow(QGraphicsView): 
    def __init__(self, parent = None): 
     super().__init__(parent) 

     self.sx = 635 
     self.sy = 475 

     scene = QGraphicsScene(0,0,self.sx,self.sy) 
     self.setScene(scene) 

     self.x = 0 
     self.y = 0 
     self.w = 30 
     self.h = 30 
     pen = QPen(QColor('dodgerblue')) 
     #pen = QPen(QColor(Qt.green)) 
     brush = QBrush(pen.color()) 
     #brush = QBrush(pen.color().darker(150)) 

     # As opposed to using QPen and QBrush, this colors the periphery only 
     #dot = scene.addEllipse(self.x, self.y, self.w, self.h, QColor('dodgerblue')) 

     self.dot = scene.addEllipse(self.x, self.y, self.w, self.h, pen, brush) 
     self.dot.setFlag(QGraphicsItem.ItemIsMovable) 


if __name__ == '__main__': 
    import sys 

    fps = 50 
    refresh_period = 1000/fps # ms 

    app = QApplication(sys.argv) 

    gw = GameWindow() 
    gw.resize(640,480) 
    gw.show() 


    # if the steps match the gw aspect ratio, the dot will move along the main diagonal, 
    # otherwise the dot will drift 
    xstep = 4 
    ystep = 3 
    #ystep = xstep * gw.sy/gw.sx 

    def moveDot(): 
     # In place of the next four lines, one can have a function 
     # or a feed from an external source to update gw.x and gw.y 
     gw.x += xstep 
     gw.x %= gw.sx 

     gw.y += ystep 
     gw.y %= gw.sy 

     gw.dot.setRect(gw.x,gw.y,gw.w,gw.h) 

    timer = QTimer() 
    timer.timeout.connect(moveDot) 

    # Comment this line out to be able to click and drag the dot 
    timer.start(refresh_period) 

    sys.exit(app.exec_()) 
관련 문제