Solved thread in QGraphicsScene
-
MyScene *scene = new MyScene; // class MyScene inherite QGraphicsScene QGraphicsView *view = new QGraphicsView; view->setScene(scene);
The
scene
has a function which is complex and time-consuming, so I want to create a therad to sovle the function. Because the function will use the member variables, so I can't isolate this function from the calssMyScene
.There are two ways to create a thread.
One, by inheriting
QThread
, but if I do so, the classMyScene
will both inherite classQGraphicsScene
andQThread
. It's workable????Two, by inheriting
QObject
and use functionmoveToThread()
, but the premise isscene
has no parent. It's impossible,view
will be its parent.Can someone give me some advice? How do I do it by using multiple threads?
-
Hi,
Why is your MyScene class inheriting from both
QGraphicsScene
andQThread
? -
@SGaist Because I want to use thread.
-
-
@jsulm The scene has a function which is complex and time-consuming, so I want to create a therad to sovle the function. Because the function will use the member variables, so I can't isolate this function from the calss MyScene.
-
@Limer Does it really need to use member variables? It would be better to pass the values of this member variables to this function as parameters. I'm not completely sure, but most probably it is not allowed to access these classes from several threads (this is the case for widgets for sure).
-
@jsulm Yes, it have to use member variables.
I‘ve thought about passing the values of this member too,,,but I want to know whether there is an anthor better solution.
-
What are these member variables that you need to pass ?
-
@SGaist About 1000+ QGraphicsRectItems in a QList, and several variables(bool).
-
I don't see anything that you can't pass to your thread for processing provided that you don't modify a GUI element in it.
[edited SGaist]
-
@SGaist You mean I can pass these variables to thread?
This is my first try to use thread, so I don't know whether my solution is right or optimal.
-
Most anything related to QGraphicsView has to run in the main thread. Handing over any pointers to a class derived from QGraphicsItem to a thread is risky.
I find it better to completely separate the complex function from any GUI-related classes:
- Extract the data you need from your GraphicsScene into a custom-made data class
- Hand over that data class to a thread for processing
- Extract the results and apply them to your scene.
If you process a list of items, and you need to apply a function to each item within the list, then you may want to take a look at QtConcurrentMap. It offers a much simpler interface for such use cases.
-
@Asperamanca Thanks for your solution.