Skip to content
Advertisement

Drawing a shape over a widget

I need to be able to draw a circle/line on top of another widget, but every time I try, it goes behind. I have read lots of posts about using QPainter over widgets but I still can’t get it to work.

The following is a minimal example of my app, and I just want to figure out where to put a paintevent function for it to work properly.

My end goal is to allow users to draw thermo sudokus such as this – thermo

But I think that if I can work out how to draw anything on top of my SudokuGrid, I can work the rest out

JavaScript

Advertisement

Answer

You can reimplement the paintEvent in SudokuCell or SudokuGrid, but in either case SudokuCell needs to have a transparent background so the thermo drawings will be painted on top of everything except for the QLineEdit text editor. I chose SudokuCell.

JavaScript

Notice that super().paintEvent(event) is called after the custom painting, so the text editor will be visible on top of anything painted. If the background was left white it would cover the custom painting. The SudokuGrid class has methods to add a line or ellipse to any cell specified by row and column.

JavaScript

The *line arguments for SudokuGrid.add_line() are intended to be tuples in the range 0-1 as a simple key to define the elements of the line for a QPainterPath (similar to that of a gradient — 0 = left/top, 0.5 = center, 1 = right/bottom).

JavaScript

And here is how it might be used in MainWindow. Of course you may go about adding the lines and ellipses to the grid in an entirely different way that better suits your program, the primary purpose was to show how to achieve the painting “on top of the widget”.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement