PDA

View Full Version : Constructing a custom widget in QGraphicsScene



illuzioner1
1st October 2019, 17:00
Hello!

I am making an audio app in PyQt that will display custom graphs and I'm trying to use the QGraphicsScene. I plan to have the timeline on top and the graph just below, with the y-axis always visible on the left (despite horizontal scrolling). There won't be a vertical scrollbar. I thought using a vertical graphics layout might be just what I need.

It seemed like QGraphicsWidget was the natural choice to subclass since QWidget is where custom widgets are made. However, as soon as I started, I couldn't find out how to paint the QGraphicsWidget. There's no paint event that I could find. I thought about creating a pixmap and adding it as a child, butI also couldn't find out how to add a child widget except upon creation of the child. This widget should scale, but it will need to change width as someone zooms in and out of the graph.

Then I tried using a regular QWidget and add it to the scene, but the graphics layout didn't recognize it.

I tried pyqtgraph, but there are too many changes I'm making and it's hard to find resources and help on it.

So what is the best approach to create such a widget? If I use QGraphicsWidget, how do I paint it? I will also need to add all the numbers and lines on the timeline.

Thanks!

d_stranz
1st October 2019, 18:35
QGraphicsWidget inherits from QGraphicsObject, which inherits from QGraphicsItem, which has a QGraphicsItem::paint() virtual method.

However for your purposes you might find is easier to use QGraphicsProxyWidget to host a ready-to-go scientific graphics widget like Qwt (https://qwt.sourceforge.io/) or QCustomPlot (https://www.qcustomplot.com/) instead of rolling your own.

illuzioner1
1st October 2019, 18:59
Thank you for the response. So it's paint() instead of paintEvent().

I'd be happy to try QCustomPlot and Qwt, but from looking at those links they are C++ projects whereas I'm working in PyQt5. That may be why pyqtgraph was built.

Is there a way to use either of those projects in PyQt?

Also, can you please tell me how to add child widgets to QGraphicsWidget?
Thanks!

d_stranz
1st October 2019, 20:50
There is a PythonQwt project.


Also, can you please tell me how to add child widgets to QGraphicsWidget?

QGraphicsWidget is a base class, meant to be derived from to add custom painting and other features. It isn't of much direct use as far as I can see. If you want to embed an existing QWidget in a QGraphicsScene, then QGraphicsProxyWidget is what you want. Otherwise, you have to dip into C++ and write your own.

If you don't need all of the signal / slot / event handling that QGraphicsWidget provides (by virtue of inheriting from QObject) and you want to write your own graphics, you should probably start by deriving from QGraphicsItem or one of its sub-classes.