Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you draw a grid and rectangles in Python?

What Python-related code (PyGTK, Glade, Tkinter, PyQT, wxPython, Cairo, ...) could you easily use to create a GUI to do some or all of the following?

  1. Part of the GUI has an immovable square grid.
  2. The user can press a button to create a resizable rectangle.
  3. The user can drag the rectangle anywhere on the grid, and it will snap to the grid.
like image 518
Winston C. Yang Avatar asked Aug 21 '10 20:08

Winston C. Yang


1 Answers

The DiagramScene Eaxmple that comes with PyQt implements much of the functionality you want. It has a fixed background grid, you can create a rectangle object but it's not resizable and doesn't snap to grid.

This SO article has advice on resizing graphical objects with the mouse. It's for C++ Qt but the technique should be easy to replicate in PyQt.

For snap-to-grid I don't think there is any built-in functionality. You would probably need to reimplement the itemChange(GraphicsItemChange change, const QVariant &value) function. Pseudocode:

if (object not possitioned exactly on the grid):
    (possition the item on the grid)

Repossitioning the item will cause itemChange to get called again, but that's ok because the item will be possitioned correctly and won't be moved again, so you'll not be stuck in an endless loop.

like image 148
Simon Hibbs Avatar answered Oct 02 '22 16:10

Simon Hibbs