move QGraphicsItem continuously in QGraphicsScene and check CollisionHow can I do a line break (line continuation) in Python?How do I check if a list is empty?How do I check whether a file exists without exceptions?What's the canonical way to check for type in Python?How do I check if a string is a number (float)?How do I check what version of Python is running my script?Check if a given key already exists in a dictionaryChecking whether a variable is an integer or notMost elegant way to check if the string is empty in Python?Prevent QGraphicsItem from moving outside of QGraphicsScene

Are there vaccine ingredients which may not be disclosed ("hidden", "trade secret", or similar)?

Double underlining a result in a system of equations with calculation steps on the right side

Company stopped paying my salary. What are my options?

And now you see it II (the B side)

What can cause an unfrozen indoor copper drain pipe to crack?

Which spells are in some way related to shadows or the Shadowfell?

Why do the Avengers care about returning these items in Endgame?

What is a good way to allow only one non null field in an object

Renting a house to a graduate student in my department

A Latin text with dependency tree

What is the minimum required technology to reanimate someone who has been cryogenically frozen?

I might have messed up in the 'Future Work' section of my thesis

Add Columns to .csv from Multiple Files

Two (probably) equal real numbers which are not proved to be equal?

Thawing Glaciers return to hand interaction

How long can fsck take on a 30 TB volume?

How do I minimise waste on a flight?

resoldering copper waste pipe

Why use steam instead of just hot air?

Is there an application which does HTTP PUT?

Gift for mentor after his thesis defense?

Does Thread.yield() do anything if we have enough processors to service all threads?

How come mathematicians published in Annals of Eugenics?

Can a planet still function with a damaged moon?



move QGraphicsItem continuously in QGraphicsScene and check Collision


How can I do a line break (line continuation) in Python?How do I check if a list is empty?How do I check whether a file exists without exceptions?What's the canonical way to check for type in Python?How do I check if a string is a number (float)?How do I check what version of Python is running my script?Check if a given key already exists in a dictionaryChecking whether a variable is an integer or notMost elegant way to check if the string is empty in Python?Prevent QGraphicsItem from moving outside of QGraphicsScene






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















about 3 weeks ago I asked for changing a GraphicsItem in a GraphicsScene. It was a line and the solution was: self.setLine(..). Now I try to understand, moving it continuously. So I have a graphicsview gvCanvas and within a scene and initialize rectangles, lines... It works



For moving a rectange I have the following code for Class myRect with an __init__ and a movemyrect



class myRect(QtWidgets.QGraphicsRectItem):
def __init__(self, QRectF): # *args):
QtWidgets.QGraphicsRectItem.__init__(self)
self.setRect(QRectF)
self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
self.setPen(QtGui.QPen(QtCore.Qt.white, 3))

def movemyRect(self, x, y, angl):
myyrs = QtWidgets.QGraphicsRectItem.rect(self) #(self.myyr) #line(items[0])
ptrr = myyrs.bottomLeft()
xpos = ptrr.x() + x #+x
ypos = ptrr.y() - y
ptnew=QtCore.QPoint(xpos,ypos)
myr = QtCore.QRectF(ptnew, QtCore.QSizeF(15,15))
self.setRotation(angl)
self.setRect(myr)
self.update()


I then try to move around a rect



 xm =20
ym = 20
for i in range(1,5):
time.sleep(0.8)
print("nachsleep",i)
self.rect2.movemyRect(xm, ym, 10)
myyrs = QtWidgets.QGraphicsRectItem.rect(self.rect2)
self.rect2.setRect(myyrs)
self.scene.update()
listtreffer = self.scene.collidingItems(self.lnk, mode=Qt.IntersectsItemShape)
for treffer in listtreffer:
print("treffer", treffer)


The loop works, but the moved and rotated rectangle appears changed only at the end of the loop on my scene, not after every step. I thought, with the statement "setRect..." it should work at every walk through the loop. Also the scene.update() doesn't help.



If I do it without loop, it works, too.



What is wrong, that the moved rectangle does not appear on every step in the loop?



The statement with checking collision works correct in every step.



Here is an additional question: if I only want the collision checked of this rectangle, would it be better to define a sort of collision-check within the class definition instead of within this loop?



(I also try do do the same with an animation and QPropertyAnimantion. There i fail to fire or get the advance-statement running. to check collision, even when moving aroud works. But i think, for this i should open an new question)










share|improve this question






























    2















    about 3 weeks ago I asked for changing a GraphicsItem in a GraphicsScene. It was a line and the solution was: self.setLine(..). Now I try to understand, moving it continuously. So I have a graphicsview gvCanvas and within a scene and initialize rectangles, lines... It works



    For moving a rectange I have the following code for Class myRect with an __init__ and a movemyrect



    class myRect(QtWidgets.QGraphicsRectItem):
    def __init__(self, QRectF): # *args):
    QtWidgets.QGraphicsRectItem.__init__(self)
    self.setRect(QRectF)
    self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
    self.setPen(QtGui.QPen(QtCore.Qt.white, 3))

    def movemyRect(self, x, y, angl):
    myyrs = QtWidgets.QGraphicsRectItem.rect(self) #(self.myyr) #line(items[0])
    ptrr = myyrs.bottomLeft()
    xpos = ptrr.x() + x #+x
    ypos = ptrr.y() - y
    ptnew=QtCore.QPoint(xpos,ypos)
    myr = QtCore.QRectF(ptnew, QtCore.QSizeF(15,15))
    self.setRotation(angl)
    self.setRect(myr)
    self.update()


    I then try to move around a rect



     xm =20
    ym = 20
    for i in range(1,5):
    time.sleep(0.8)
    print("nachsleep",i)
    self.rect2.movemyRect(xm, ym, 10)
    myyrs = QtWidgets.QGraphicsRectItem.rect(self.rect2)
    self.rect2.setRect(myyrs)
    self.scene.update()
    listtreffer = self.scene.collidingItems(self.lnk, mode=Qt.IntersectsItemShape)
    for treffer in listtreffer:
    print("treffer", treffer)


    The loop works, but the moved and rotated rectangle appears changed only at the end of the loop on my scene, not after every step. I thought, with the statement "setRect..." it should work at every walk through the loop. Also the scene.update() doesn't help.



    If I do it without loop, it works, too.



    What is wrong, that the moved rectangle does not appear on every step in the loop?



    The statement with checking collision works correct in every step.



    Here is an additional question: if I only want the collision checked of this rectangle, would it be better to define a sort of collision-check within the class definition instead of within this loop?



    (I also try do do the same with an animation and QPropertyAnimantion. There i fail to fire or get the advance-statement running. to check collision, even when moving aroud works. But i think, for this i should open an new question)










    share|improve this question


























      2












      2








      2








      about 3 weeks ago I asked for changing a GraphicsItem in a GraphicsScene. It was a line and the solution was: self.setLine(..). Now I try to understand, moving it continuously. So I have a graphicsview gvCanvas and within a scene and initialize rectangles, lines... It works



      For moving a rectange I have the following code for Class myRect with an __init__ and a movemyrect



      class myRect(QtWidgets.QGraphicsRectItem):
      def __init__(self, QRectF): # *args):
      QtWidgets.QGraphicsRectItem.__init__(self)
      self.setRect(QRectF)
      self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
      self.setPen(QtGui.QPen(QtCore.Qt.white, 3))

      def movemyRect(self, x, y, angl):
      myyrs = QtWidgets.QGraphicsRectItem.rect(self) #(self.myyr) #line(items[0])
      ptrr = myyrs.bottomLeft()
      xpos = ptrr.x() + x #+x
      ypos = ptrr.y() - y
      ptnew=QtCore.QPoint(xpos,ypos)
      myr = QtCore.QRectF(ptnew, QtCore.QSizeF(15,15))
      self.setRotation(angl)
      self.setRect(myr)
      self.update()


      I then try to move around a rect



       xm =20
      ym = 20
      for i in range(1,5):
      time.sleep(0.8)
      print("nachsleep",i)
      self.rect2.movemyRect(xm, ym, 10)
      myyrs = QtWidgets.QGraphicsRectItem.rect(self.rect2)
      self.rect2.setRect(myyrs)
      self.scene.update()
      listtreffer = self.scene.collidingItems(self.lnk, mode=Qt.IntersectsItemShape)
      for treffer in listtreffer:
      print("treffer", treffer)


      The loop works, but the moved and rotated rectangle appears changed only at the end of the loop on my scene, not after every step. I thought, with the statement "setRect..." it should work at every walk through the loop. Also the scene.update() doesn't help.



      If I do it without loop, it works, too.



      What is wrong, that the moved rectangle does not appear on every step in the loop?



      The statement with checking collision works correct in every step.



      Here is an additional question: if I only want the collision checked of this rectangle, would it be better to define a sort of collision-check within the class definition instead of within this loop?



      (I also try do do the same with an animation and QPropertyAnimantion. There i fail to fire or get the advance-statement running. to check collision, even when moving aroud works. But i think, for this i should open an new question)










      share|improve this question
















      about 3 weeks ago I asked for changing a GraphicsItem in a GraphicsScene. It was a line and the solution was: self.setLine(..). Now I try to understand, moving it continuously. So I have a graphicsview gvCanvas and within a scene and initialize rectangles, lines... It works



      For moving a rectange I have the following code for Class myRect with an __init__ and a movemyrect



      class myRect(QtWidgets.QGraphicsRectItem):
      def __init__(self, QRectF): # *args):
      QtWidgets.QGraphicsRectItem.__init__(self)
      self.setRect(QRectF)
      self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
      self.setPen(QtGui.QPen(QtCore.Qt.white, 3))

      def movemyRect(self, x, y, angl):
      myyrs = QtWidgets.QGraphicsRectItem.rect(self) #(self.myyr) #line(items[0])
      ptrr = myyrs.bottomLeft()
      xpos = ptrr.x() + x #+x
      ypos = ptrr.y() - y
      ptnew=QtCore.QPoint(xpos,ypos)
      myr = QtCore.QRectF(ptnew, QtCore.QSizeF(15,15))
      self.setRotation(angl)
      self.setRect(myr)
      self.update()


      I then try to move around a rect



       xm =20
      ym = 20
      for i in range(1,5):
      time.sleep(0.8)
      print("nachsleep",i)
      self.rect2.movemyRect(xm, ym, 10)
      myyrs = QtWidgets.QGraphicsRectItem.rect(self.rect2)
      self.rect2.setRect(myyrs)
      self.scene.update()
      listtreffer = self.scene.collidingItems(self.lnk, mode=Qt.IntersectsItemShape)
      for treffer in listtreffer:
      print("treffer", treffer)


      The loop works, but the moved and rotated rectangle appears changed only at the end of the loop on my scene, not after every step. I thought, with the statement "setRect..." it should work at every walk through the loop. Also the scene.update() doesn't help.



      If I do it without loop, it works, too.



      What is wrong, that the moved rectangle does not appear on every step in the loop?



      The statement with checking collision works correct in every step.



      Here is an additional question: if I only want the collision checked of this rectangle, would it be better to define a sort of collision-check within the class definition instead of within this loop?



      (I also try do do the same with an animation and QPropertyAnimantion. There i fail to fire or get the advance-statement running. to check collision, even when moving aroud works. But i think, for this i should open an new question)







      python pyqt5 qgraphicsscene qgraphicsitem






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 23 at 8:23









      eyllanesc

      91.8k123565




      91.8k123565










      asked Mar 21 at 9:19









      user3367867user3367867

      1631312




      1631312






















          1 Answer
          1






          active

          oldest

          votes


















          1














          In a GUI you should never use time.sleep since it blocks the eventloop and consequently the window freezes preventing the GUI from being repainted. In Qt you have to do the actions using events, for example in the following code each time the timer is triggered, change the position. To make smooth movement use a QVariantAnimation, QPropertyAnimation can not be used since the QGraphicsItem are not QObjects and the position is not a qproperty.



          import random
          from functools import partial
          from PyQt5 import QtCore, QtGui, QtWidgets

          class RectItem(QtWidgets.QGraphicsRectItem):
          def __init__(self, rect=QtCore.QRectF()):
          super(RectItem, self).__init__(rect)
          self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
          self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)
          self.setPen(QtGui.QPen(QtCore.Qt.red, 3))
          self._pos_animation = QtCore.QVariantAnimation()
          self._pos_animation.valueChanged.connect(self.setPos)

          def move_smooth(self, end, duration=1000):
          if self._pos_animation.state() == QtCore.QAbstractAnimation.Running:
          self._pos_animation.stop()
          self._pos_animation.setDuration(duration)
          self._pos_animation.setStartValue(self.pos())
          self._pos_animation.setEndValue(end)
          self._pos_animation.start()

          def itemChange(self, change, value):
          if change ==QtWidgets.QGraphicsItem.ItemPositionChange:
          color = QtGui.QColor(QtCore.Qt.red)
          if self.scene().collidingItems(self):
          color = QtGui.QColor(QtCore.Qt.green)
          self.setPen(QtGui.QPen(color, 3))
          return super(RectItem, self).itemChange(change, value)

          def move_pos(scene):
          for it in scene.items():
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          if hasattr(it, 'move_smooth'):
          it.move_smooth(pos, 1000)

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          app.setStyle('fusion')
          scene = QtWidgets.QGraphicsScene(-100, -100, 200, 200)
          scene.setBackgroundBrush(QtCore.Qt.gray)
          view = QtWidgets.QGraphicsView(scene)
          view.resize(640, 480)
          view.show()
          l = []
          for _ in range(4):
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          it = RectItem(QtCore.QRectF(-20, -20, 40, 40))
          scene.addItem(it)
          it.setPos(pos)
          l.append(it)
          wrapper = partial(move_pos, scene)
          timer = QtCore.QTimer(interval=3000, timeout=wrapper)
          timer.start()
          wrapper()
          sys.exit(app.exec_())





          share|improve this answer

























          • thank you. very fine

            – user3367867
            Mar 24 at 13:51











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55277098%2fmove-qgraphicsitem-continuously-in-qgraphicsscene-and-check-collision%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          In a GUI you should never use time.sleep since it blocks the eventloop and consequently the window freezes preventing the GUI from being repainted. In Qt you have to do the actions using events, for example in the following code each time the timer is triggered, change the position. To make smooth movement use a QVariantAnimation, QPropertyAnimation can not be used since the QGraphicsItem are not QObjects and the position is not a qproperty.



          import random
          from functools import partial
          from PyQt5 import QtCore, QtGui, QtWidgets

          class RectItem(QtWidgets.QGraphicsRectItem):
          def __init__(self, rect=QtCore.QRectF()):
          super(RectItem, self).__init__(rect)
          self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
          self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)
          self.setPen(QtGui.QPen(QtCore.Qt.red, 3))
          self._pos_animation = QtCore.QVariantAnimation()
          self._pos_animation.valueChanged.connect(self.setPos)

          def move_smooth(self, end, duration=1000):
          if self._pos_animation.state() == QtCore.QAbstractAnimation.Running:
          self._pos_animation.stop()
          self._pos_animation.setDuration(duration)
          self._pos_animation.setStartValue(self.pos())
          self._pos_animation.setEndValue(end)
          self._pos_animation.start()

          def itemChange(self, change, value):
          if change ==QtWidgets.QGraphicsItem.ItemPositionChange:
          color = QtGui.QColor(QtCore.Qt.red)
          if self.scene().collidingItems(self):
          color = QtGui.QColor(QtCore.Qt.green)
          self.setPen(QtGui.QPen(color, 3))
          return super(RectItem, self).itemChange(change, value)

          def move_pos(scene):
          for it in scene.items():
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          if hasattr(it, 'move_smooth'):
          it.move_smooth(pos, 1000)

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          app.setStyle('fusion')
          scene = QtWidgets.QGraphicsScene(-100, -100, 200, 200)
          scene.setBackgroundBrush(QtCore.Qt.gray)
          view = QtWidgets.QGraphicsView(scene)
          view.resize(640, 480)
          view.show()
          l = []
          for _ in range(4):
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          it = RectItem(QtCore.QRectF(-20, -20, 40, 40))
          scene.addItem(it)
          it.setPos(pos)
          l.append(it)
          wrapper = partial(move_pos, scene)
          timer = QtCore.QTimer(interval=3000, timeout=wrapper)
          timer.start()
          wrapper()
          sys.exit(app.exec_())





          share|improve this answer

























          • thank you. very fine

            – user3367867
            Mar 24 at 13:51















          1














          In a GUI you should never use time.sleep since it blocks the eventloop and consequently the window freezes preventing the GUI from being repainted. In Qt you have to do the actions using events, for example in the following code each time the timer is triggered, change the position. To make smooth movement use a QVariantAnimation, QPropertyAnimation can not be used since the QGraphicsItem are not QObjects and the position is not a qproperty.



          import random
          from functools import partial
          from PyQt5 import QtCore, QtGui, QtWidgets

          class RectItem(QtWidgets.QGraphicsRectItem):
          def __init__(self, rect=QtCore.QRectF()):
          super(RectItem, self).__init__(rect)
          self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
          self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)
          self.setPen(QtGui.QPen(QtCore.Qt.red, 3))
          self._pos_animation = QtCore.QVariantAnimation()
          self._pos_animation.valueChanged.connect(self.setPos)

          def move_smooth(self, end, duration=1000):
          if self._pos_animation.state() == QtCore.QAbstractAnimation.Running:
          self._pos_animation.stop()
          self._pos_animation.setDuration(duration)
          self._pos_animation.setStartValue(self.pos())
          self._pos_animation.setEndValue(end)
          self._pos_animation.start()

          def itemChange(self, change, value):
          if change ==QtWidgets.QGraphicsItem.ItemPositionChange:
          color = QtGui.QColor(QtCore.Qt.red)
          if self.scene().collidingItems(self):
          color = QtGui.QColor(QtCore.Qt.green)
          self.setPen(QtGui.QPen(color, 3))
          return super(RectItem, self).itemChange(change, value)

          def move_pos(scene):
          for it in scene.items():
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          if hasattr(it, 'move_smooth'):
          it.move_smooth(pos, 1000)

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          app.setStyle('fusion')
          scene = QtWidgets.QGraphicsScene(-100, -100, 200, 200)
          scene.setBackgroundBrush(QtCore.Qt.gray)
          view = QtWidgets.QGraphicsView(scene)
          view.resize(640, 480)
          view.show()
          l = []
          for _ in range(4):
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          it = RectItem(QtCore.QRectF(-20, -20, 40, 40))
          scene.addItem(it)
          it.setPos(pos)
          l.append(it)
          wrapper = partial(move_pos, scene)
          timer = QtCore.QTimer(interval=3000, timeout=wrapper)
          timer.start()
          wrapper()
          sys.exit(app.exec_())





          share|improve this answer

























          • thank you. very fine

            – user3367867
            Mar 24 at 13:51













          1












          1








          1







          In a GUI you should never use time.sleep since it blocks the eventloop and consequently the window freezes preventing the GUI from being repainted. In Qt you have to do the actions using events, for example in the following code each time the timer is triggered, change the position. To make smooth movement use a QVariantAnimation, QPropertyAnimation can not be used since the QGraphicsItem are not QObjects and the position is not a qproperty.



          import random
          from functools import partial
          from PyQt5 import QtCore, QtGui, QtWidgets

          class RectItem(QtWidgets.QGraphicsRectItem):
          def __init__(self, rect=QtCore.QRectF()):
          super(RectItem, self).__init__(rect)
          self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
          self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)
          self.setPen(QtGui.QPen(QtCore.Qt.red, 3))
          self._pos_animation = QtCore.QVariantAnimation()
          self._pos_animation.valueChanged.connect(self.setPos)

          def move_smooth(self, end, duration=1000):
          if self._pos_animation.state() == QtCore.QAbstractAnimation.Running:
          self._pos_animation.stop()
          self._pos_animation.setDuration(duration)
          self._pos_animation.setStartValue(self.pos())
          self._pos_animation.setEndValue(end)
          self._pos_animation.start()

          def itemChange(self, change, value):
          if change ==QtWidgets.QGraphicsItem.ItemPositionChange:
          color = QtGui.QColor(QtCore.Qt.red)
          if self.scene().collidingItems(self):
          color = QtGui.QColor(QtCore.Qt.green)
          self.setPen(QtGui.QPen(color, 3))
          return super(RectItem, self).itemChange(change, value)

          def move_pos(scene):
          for it in scene.items():
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          if hasattr(it, 'move_smooth'):
          it.move_smooth(pos, 1000)

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          app.setStyle('fusion')
          scene = QtWidgets.QGraphicsScene(-100, -100, 200, 200)
          scene.setBackgroundBrush(QtCore.Qt.gray)
          view = QtWidgets.QGraphicsView(scene)
          view.resize(640, 480)
          view.show()
          l = []
          for _ in range(4):
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          it = RectItem(QtCore.QRectF(-20, -20, 40, 40))
          scene.addItem(it)
          it.setPos(pos)
          l.append(it)
          wrapper = partial(move_pos, scene)
          timer = QtCore.QTimer(interval=3000, timeout=wrapper)
          timer.start()
          wrapper()
          sys.exit(app.exec_())





          share|improve this answer















          In a GUI you should never use time.sleep since it blocks the eventloop and consequently the window freezes preventing the GUI from being repainted. In Qt you have to do the actions using events, for example in the following code each time the timer is triggered, change the position. To make smooth movement use a QVariantAnimation, QPropertyAnimation can not be used since the QGraphicsItem are not QObjects and the position is not a qproperty.



          import random
          from functools import partial
          from PyQt5 import QtCore, QtGui, QtWidgets

          class RectItem(QtWidgets.QGraphicsRectItem):
          def __init__(self, rect=QtCore.QRectF()):
          super(RectItem, self).__init__(rect)
          self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
          self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)
          self.setPen(QtGui.QPen(QtCore.Qt.red, 3))
          self._pos_animation = QtCore.QVariantAnimation()
          self._pos_animation.valueChanged.connect(self.setPos)

          def move_smooth(self, end, duration=1000):
          if self._pos_animation.state() == QtCore.QAbstractAnimation.Running:
          self._pos_animation.stop()
          self._pos_animation.setDuration(duration)
          self._pos_animation.setStartValue(self.pos())
          self._pos_animation.setEndValue(end)
          self._pos_animation.start()

          def itemChange(self, change, value):
          if change ==QtWidgets.QGraphicsItem.ItemPositionChange:
          color = QtGui.QColor(QtCore.Qt.red)
          if self.scene().collidingItems(self):
          color = QtGui.QColor(QtCore.Qt.green)
          self.setPen(QtGui.QPen(color, 3))
          return super(RectItem, self).itemChange(change, value)

          def move_pos(scene):
          for it in scene.items():
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          if hasattr(it, 'move_smooth'):
          it.move_smooth(pos, 1000)

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          app.setStyle('fusion')
          scene = QtWidgets.QGraphicsScene(-100, -100, 200, 200)
          scene.setBackgroundBrush(QtCore.Qt.gray)
          view = QtWidgets.QGraphicsView(scene)
          view.resize(640, 480)
          view.show()
          l = []
          for _ in range(4):
          pos = QtCore.QPointF(*random.sample(range(-100, 200), 2))
          it = RectItem(QtCore.QRectF(-20, -20, 40, 40))
          scene.addItem(it)
          it.setPos(pos)
          l.append(it)
          wrapper = partial(move_pos, scene)
          timer = QtCore.QTimer(interval=3000, timeout=wrapper)
          timer.start()
          wrapper()
          sys.exit(app.exec_())






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 23 at 9:05

























          answered Mar 23 at 8:59









          eyllanesceyllanesc

          91.8k123565




          91.8k123565












          • thank you. very fine

            – user3367867
            Mar 24 at 13:51

















          • thank you. very fine

            – user3367867
            Mar 24 at 13:51
















          thank you. very fine

          – user3367867
          Mar 24 at 13:51





          thank you. very fine

          – user3367867
          Mar 24 at 13:51



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55277098%2fmove-qgraphicsitem-continuously-in-qgraphicsscene-and-check-collision%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해