How to drag&drop SVG elements?

I solved this problem! :slight_smile:

All you need to do is to put self.changed.connect(self.update) in the __init__ of a QGraphicsScene subclass. The rendering is then done with no visual artifacts. I’ve discovered this on my own, completely by sheer luck.

1 Like

@martin, I now only have one nasty issue to fix. If I mouse-drag a chess piece outside the scene’s bounding rect, the view scrolls the viewport. I don’t want that.

How can I have a mouse-drag to be constrained within the scene’s bounding rect (so that the view doesn’t scroll the viewport)?

I also wasn’t able to somehow disable the view from ever scrolling the viewport. Can’t be done. Please help!

You can set the size of the scene using .setSceneRect I think that should constrain it and prevent it scrolling.

I tried constraining the QGraphicsView's viewport from scrolling by calling self.setSceneRect(self.sceneRect()) in the __init__() of my QGraphicsScene() subclass. This didn’t do the trick. Scrolling the QGraphicsView's viewport is apparently so tightly embedded into Qt's Graphics View Framework that I’m really starting to think it can’t be done. I tried all sorts of tricks from forums like this, but none of those “tricks” worked, or my application crashed when doing something crazy.

My main problem is that the user of my application is able to, currently, drop a chess piece outside the scene’s bounding rect, and hence the application crashes immediately, because chessboard coordinates are, of course, not defined outside of it.

Somehow I managed it in my Solitaire app source here. I thought it was just the sceneRect, but I also fix the window size (seems weird that would be related).

Aside from that you can also constrain the positions when snapping in the squares (min/max for the board dimensions), that’ll avoid the crash at least.

1 Like

@martin, you, my friend, are absolutely amazing! Yes, your approach in the Solitaire source code solved my problem. :+1:

Now the view doesn’t scroll its viewport even if a chess piece is dragged outside the scene (the dragged chess piece is obscured). And if a chess piece is dropped outside the scene, I catch the appropriate exception (that is raised by the python-chess library) and ignore it, and redraw the chessboard, which basically puts the dragged chess piece back as it was before entering the drag operation. All is good.

To refine the user experience, I am wondering whether dragging a chess piece can be constrained to inside the scene’s rect only, because now a chess piece (when leaving the scene’s rect) is obscured. Is that something that can be done, i.e., to lock the movement of the mouse-drag operation within the bounds of the scene’s rect?