Adding multiple QGraphicsScene on QGraphicsView - qt

I am creating a GUI where user needs to interact using QGraphicsView.
So what I am doing right now is, I created QGraphicsScene and assigned it to QGraphicsView.
There are supposed to be two layers for drawing: one static and one dynamic.
Static layer is supposed to have objects that are created once at startup while dynamic layer contains multiple items (may be hundred of them) and user will interact will dynamic layer objects.
Currently I am drawing both layers on same scene which creates some lag due to large number of objects being drawn.
So question: Is there any way to assign two or more QGraphicsScene to a QGraphicsView ?

One option might be to implement your own class derived from QGraphicsScene that can then render a second 'background' scene in its drawBackground override.
class graphics_scene: public QGraphicsScene {
using super = QGraphicsScene;
public:
using super::super;
void set_background_scene (QGraphicsScene *background_scene)
{
m_background_scene = background_scene;
}
protected:
virtual void drawBackground (QPainter *painter, const QRectF &rect) override
{
if (m_background_scene) {
m_background_scene->render(painter, rect, rect);
}
}
private:
QGraphicsScene *m_background_scene = nullptr;
};
Then use as...
QGraphicsView view;
/*
* fg is the 'dynamic' layer.
*/
graphics_scene fg;
/*
* bg is the 'static' layer used as a background.
*/
QGraphicsScene bg;
bg.addText("Text Item 1")->setPos(50, 50);
bg.addText("Text Item 2")->setPos(250, 250);
fg.addText("Text Item 3")->setPos(50, 50);
fg.addText("Text Item 4")->setPos(350, 350);
view.setScene(&fg);
fg.set_background_scene(&bg);
view.show();
I've only performed basic testing but it appears to behave as expected. Not sure about any potential performance issues though.

Related

Qt Button Group over OpenGLWidget

I am designing a user interface with Qt Creator. I have a openGLwidget which covers all the form and I want to place some buttons aligned to bottom and some kind of notification frames over the widget. Is there any default way to do that?
When I try to design that on creator, I could not get rid of layout limits and don't allow me to place a widget over openglwidget.
When reading the question first, I was reading this as “How to make a QOpenGLWidget with Head-Up Display with buttons?”.
How to make a QOpenGLWidget with Head-Up Display (painted with QPainter), I once answered in SO: Paint a rect on qglwidget at specifit times. However, there was only painting – no interactive widgets.
Hence, I prepared a new sample testQGLWidgetHUDButtons.cc:
#include <QtWidgets>
class OpenGLWidget: public QOpenGLWidget, public QOpenGLFunctions {
private:
struct ClearColor {
float r, g, b;
ClearColor(): r(0.6f), g(0.8f), b(1.0f) { }
} _clearColor;
public:
OpenGLWidget(QWidget *pQParent = nullptr):
QOpenGLWidget(pQParent),
QOpenGLFunctions()
{ }
virtual ~OpenGLWidget() = default;
OpenGLWidget(const OpenGLWidget&) = delete;
OpenGLWidget& operator=(const OpenGLWidget&) = delete;
void setClearColor(float r, float g, float b);
protected:
virtual void initializeGL() override;
virtual void paintGL() override;
};
void OpenGLWidget::setClearColor(float r, float g, float b)
{
_clearColor.r = r; _clearColor.g = g; _clearColor.b = b;
update(); // force update of widget
}
void OpenGLWidget::initializeGL()
{
initializeOpenGLFunctions();
}
void OpenGLWidget::paintGL()
{
glClearColor(
_clearColor.r, _clearColor.g, _clearColor.b, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup GUI
OpenGLWidget qWin;
QGridLayout qGrid;
QPushButton qBtn1(QString::fromUtf8("Black BG"));
qGrid.addWidget(&qBtn1, 1, 1);
QPushButton qBtn2(QString::fromUtf8("White BG"));
qGrid.addWidget(&qBtn2, 1, 2);
QPushButton qBtn3(QString::fromUtf8("Blue BG"));
qGrid.addWidget(&qBtn3, 1, 3);
qGrid.setRowStretch(0, 1);
qGrid.setColumnStretch(0, 1);
qWin.setLayout(&qGrid);
qWin.show();
// install signal handlers
QObject::connect(&qBtn1, &QPushButton::clicked,
[&qWin](bool) { qWin.setClearColor(0.0f, 0.0f, 0.0f); });
QObject::connect(&qBtn2, &QPushButton::clicked,
[&qWin](bool) { qWin.setClearColor(1.0f, 1.0f, 1.0f); });
QObject::connect(&qBtn3, &QPushButton::clicked,
[&qWin](bool) { qWin.setClearColor(0.6f, 0.8f, 1.0f); });
// runtime loop
return app.exec();
}
and the project file testQGLWidgetHUDButtons.pro:
SOURCES = testQGLWidgetHUDButtons.cc
QT += widgets opengl
Compiled and tested in VS2013 on Windows 10:
It's actually quite easy – QOpenGLWidget is derived from QWidget. QWidget provides the method QWidget::setLayout(). To add child widgets, a QLayout should be used which manages layout of children in parent widget (and takes part in size negotiation when parent widget is layouted).
To keep it simple, I used a QGridLayout where buttons are placed in cells (1, 1), (1, 2), and (1, 3). Row 0 and column 0 are left empty but enabled for stetching. This results effectively in attaching the buttons in lower right corner.
When I was about to publish this answer, I took a second look onto the question and realized the Qt Button Group in title. I would've ignore it (multiple buttons are a button group?) but there is also the qbuttongroup which made me stumbling.
A QButtonGroup:
The QButtonGroup class provides a container to organize groups of button widgets.
QButtonGroup provides an abstract container into which button widgets can be placed. It does not provide a visual representation of this container (see QGroupBox for a container widget), but instead manages the states of each of the buttons in the group.
(Emphasize mine.)
So, a button group can be used e.g. to keep radio buttons in sync. It is derived from QObject and hence, neither a QWidget nor a QLayout. Thus, it's not suitable to add visible child widgets to the QOpenGLWidget.
Though I've no experiences with QCreator, I assume it should work there as well as it does in my sample:
Assign a layout to the QOpenGLWidget (e.g. QGridLayout as I did in my sample).
Add QPushButtons to this layout.
Btw. IMHO this is no specific problem about the QOpenGLWidget – it should've happend with any other QWidget as well.

QOpenGLWidget and transparency

I have small problem with QOpenGLWidget and its background color.
When I want to create semi-transparent rect on my custom QOpenGLWidget using QPainter there are 2 different results:
If MyCustomWidget have parent - on every update rect's color multiplies (and after few repaints it is opaque, like previous painting result not cleaned)
If MyCustomWidget doesn't have parent - color doesn't repaints each time
Here is code example for QPainter:
class Widget : public QOpenGLWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0)
: QOpenGLWidget(parent)
{
resize(800, 600);
Test *test = new Test(this);
}
~Widget(){}
protected:
void paintEvent(QPaintEvent *) {}
protected:
void initializeGL() {
if(paintEngine()->type() != QPaintEngine::OpenGL &&
paintEngine()->type() != QPaintEngine::OpenGL2)
qDebug() << "ERROR. Type is: " << paintEngine()->type();
}
void resizeGL(int, int) {}
void paintGL() {
QPainter p;
p.begin(this);
{
p.fillRect(rect(), Qt::white);
}
p.end();
}
private:
class Test : public QOpenGLWidget
{
public:
Test(QWidget *parent = 0) : QOpenGLWidget(parent) {
resize(100, 100);
}
protected:
void paintEvent(QPaintEvent *) {
QPainter p(this);
p.fillRect(rect(), QColor(125, 125, 125, 255/10));
}
};
};
Also by default it has black background (I don't know how to fix it. setAttribute(Qt::WA_TranslucentBackground) doesn't helps).
Also, when I'm trying to clear color using glClear it ignores alpha (both on QOpenGLWidget with parent and not). Here is Test class from previous code, but now it is using opengl to clear color:
class Test : public QOpenGLWidget
{
public:
Test(QWidget *parent = 0) : QOpenGLWidget(parent) {
resize(100, 100);
}
void initializeGL() {
QOpenGLFunctions *f = context()->functions();
f->glClearColor(0.0f, 1.0f, 0.0f, 0.1f);
}
void paintGL() {
QOpenGLFunctions *f = context()->functions();
f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
};
How can I fix this problems?
I'm using Qt 5.5.0, Windows 10, MinGW 4.9.2
Xeed is correct when saying the QOpenGLWidget is painted first.
I'm not an expert but I think I found the solution. You need to set a widget attribute to always make the widget stacked on top (think of the widgets as layers on the window). Here is a link to where I got the following information:
P.S. As mentioned in the QQuickWidget post, there is a limitation regarding semi-transparency when using QQuickWidget or QOpenGLWidget as child widgets. For applications that absolutely need this, Qt 5.4 offers a workaround: the newly introduced Qt::WA_AlwaysStackOnTop widget attribute. This, at the expense of breaking the stacking order for other types of layouts, makes it possible to have a semi-transparent QQuickWidget or QOpenGLWidget with other widgets visible underneath. Of course, if the intention is only to make other applications on the desktop visible underneath, then the Qt::WA_TranslucentBackground attribute is sufficient
Solution in Python:
set attribute of OpenGL widget
setAttribute(Qt.WA_AlwaysStackOnTop)
Now the OpenGL widget is considered 'on top' in the window. Use 'glClearColor' function and specify the alpha channel to be zero (0.0).
glClearColor(0.0, 0.0, 0.0, 0.0)
I'm not sure how to write that in other languages but this worked for me. The OpenGL widget no longer has the default black background. It is transparent! Hope this helps.
As far as I know the QOpenGLWidget is always drawn first. Therefore you cannot show any widgets layered below. I'm currently looking into the same issue. I'll report back, when I find any solution.
I've had similar issue with QOpenGLWidget not repainting correctly in transparent areas and decided to switch to QOpenGLWindow wrapped inside QWidget::createWindowContainer()

How to animate the outline of a QGraphicsItem in real time?

I am designing a timer with Qt. With QGraphicsEllipseItem, I drew a circle and now I need to animate the QPen around this circle (change color) every second. I found QGraphicsPathItem, but I need some examples on how to move forward. Can anyone show me an example?
You have two problems:
QGraphicsEllipseItem is not a QObject so QPropertyAnimation can't be used directly on this item
QGraphicsItemAnimation doesn't cover property you want to animate.
What you can do?
IMO best approach is to provide some custom QObject on which you could do this animation. You can inherit QObject or use fake QGraphicsObject (which is a QObject).
class ShapeItemPenAnimator : public QGraphicsObject {
Q_OBJECT
private:
QAbstractGraphicsShapeItem *mParent;
QPropertyAnimation *mAnimation;
public:
QPROPERTY(QColor penColor
READ penColor
WRITE setPenColor)
explicit ShapeItemPenAnimator(QAbstractGraphicsShapeItem * parent)
: QGraphicsObject(parent)
, mParent(parent) {
setFlags(QGraphicsItem::ItemHasNoContents);
mAnimation = new QPropertyAnimation(this, "penColor", this);
}
QColor penColor() const {
return mParent->pen().color();
}
public slots:
void setPenColor(const QColor &color) {
QPen pen(mParent->pen());
pen.setColor(color);
mParent->setPen(pen);
}
public:
void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0) {
}
QRectF boundingRect() const {
return QRectF();
}
QPropertyAnimation *animation() const {
return mAnimation;
}
}
Now you just attach this object to your QGraphicsEllipseItem and set animation you need.
// yourEllipse
ShapeItemPenAnimator *animator = new ShapeItemPenAnimator(yourEllipse);
animator->animation()->setEndValue(....);
animator->animation()->setStartValue(....);
animator->animation()->setDuration(....);
animator->animation()->setEasingCurve(....);
There are several classes helping with animations of QGraphicsItem in Qt. I suggest looking into QGraphicsItemAnimation and QPropertyAnimation. You can use the second one to animate the color of an item. Here is an example of using QPropertyAnimation:
How to make Qt widgets fade in or fade out?

Efficient way of displaying a continuous stream of QImages

I am currently using a QLabel to do this, but this seems to be rather slow:
void Widget::sl_updateLiveStreamLabel(spImageHolder_t _imageHolderShPtr) //slot
{
QImage * imgPtr = _imageHolderShPtr->getImagePtr();
m_liveStreamLabel.setPixmap( QPixmap::fromImage(*imgPtr).scaled(this->size(), Qt::KeepAspectRatio, Qt::FastTransformation) );
m_liveStreamLabel.adjustSize();
}
Here I am generating a new QPixmap object for each new image that arrives. Since QPixmap operations are restricted to the GUI Thread, this also makes the GUI feel poorly responsive.
I've seen there are already some discussions on this, most of them advising to use QGraphicsView or QGLWidget, but I have not been able to find a quick example how to properly use those, which would be what I am looking for.
I'd appreciate any help.
QPixmap::fromImage is not the only problem. Using QPixmap::scaled or QImage::scaled also should be avoided. However you can't display QImage directly in QLabel or QGraphicsView. Here is my class that display QImage directly and scales it to the size of the widget:
Header:
class ImageDisplay : public QWidget {
Q_OBJECT
public:
ImageDisplay(QWidget* parent = 0);
void setImage(QImage* image);
private:
QImage* m_image;
protected:
void paintEvent(QPaintEvent* event);
};
Source:
ImageDisplay::ImageDisplay(QWidget *parent) : QWidget(parent) {
m_image = 0;
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
}
void ImageDisplay::setImage(QImage *image) {
m_image = image;
repaint();
}
void ImageDisplay::paintEvent(QPaintEvent*) {
if (!m_image) { return; }
QPainter painter(this);
painter.drawImage(rect(), *m_image, m_image->rect());
}
I tested it on 3000x3000 image scaled down to 600x600 size. It gives 40 FPS, while QLabel and QGraphicsView (even with fast image transformation enabled) gives 15 FPS.
Setting up a QGraphicsView and QGraphicsScene is quite straight-forward: -
int main( int argc, char **argv )
{
QApplication app(argc, argv);
// Create the scene and set its dimensions
QGraphicsScene scene;
scene.setSceneRect( 0.0, 0.0, 400.0, 400.0 );
// create an item that will hold an image
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(0);
// load an image and set it to the pixmapItem
QPixmap pixmap("pathToImage.png") // example filename pathToImage.png
item->setPixmap(pixmap);
// add the item to the scene
scene.addItem(item);
item->setPos(200,200); // set the item's position in the scene
// create a view to look into the scene
QGraphicsView view( &scene );
view.setRenderHints( QPainter::Antialiasing );
view.show();
return app.exec();
}
I recommend not use QLabel but write own class. Every call of setPixmap causes layout system to recalculate sizes of items and this can propagate to topmost parent (QMainWindow) and this is quite big overhead.
Conversion and scaling also is a bit costly.
Finally best approach is to use profiler to detect where is the biggest problem.

setpixel of QGraphicsScene in Qt

It's simple to draw line or ellipse just by using scene.addellipse(), etc.
QGraphicsScene scene(0,0,800,600);
QGraphicsView view(&scene);
scene.addText("Hello, world!");
QPen pen(Qt::green);
scene.addLine(0,0,200,200,pen);
scene.addEllipse(400,300,100,100,pen);
view.show();
now what should i do to set some pixel color? may i use a widget like qimage? by the way performance is an issue for me.thanks
I think that performing pixel manipulation on a QImage would slow down your application quite a lot. A good alternative is to subclasse QGraphicsItem in a new class, something like QGraphicsPixelItem, and implement the paint function like this:
// code untested
void QGraphicsPixelItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0)
{
painter->save();
foreach(const QPoint& p, pointList) {
// set your pen color etc.
painter->drawPoint(p);
}
painter->restore();
}
where pointList is some kind of container that you use to store the position of the pixels you want to draw.

Resources