Connecting a signal from a QGraphicsItem inside QGraphicsView
-
In my main window, I have called a subclass of QGraphicsView. And inside my custom QGraphicsView class, I have added a subclass of QGraphicsItem. In the custom QGraphicsItem class, I have a function that emits a signal. I want to catch this signal back in my main window, but I don't know how to connect to it. I tried using the graphicsView object as the signal sender but it doesn't work.
main_window.cpp
MyGraphicsView myView = new MyGraphicsView(); connect(m_ui.myView, &MyGraphicsView::mySignal, this, &MyMainWindow::mySlot)
MyGraphicsView .cpp
class MyGraphicsView : public QGraphicsView { ... scene = new QGraphicsScene(this); myItem = new MyGraphicsItem(); scene->addItem(myItem); }
MyGraphicsItem.cpp
class MyGraphicsItem: public QGraphicsItem { Q_OBJECT ... void myFunction() { emit mySignal(); } }
I'm getting the error "no member named mySignal in MyGraphicsView". I don't know how to point to the graphicsItem as the signal sender from the main window.
-
Hi,
@lansing said in Connecting a signal from a QGraphicsItem inside QGraphicsView:MyGraphicsView myView = new MyGraphicsView();
connect(m_ui.myView, &MyGraphicsView::mySignal, this, &MyMainWindow::mySlot)
myView and m_ui.myView are not the same object and likely not from the same class.
-
@SGaist said in Connecting a signal from a QGraphicsItem inside QGraphicsView:
Hi,
@lansing said in Connecting a signal from a QGraphicsItem inside QGraphicsView:MyGraphicsView myView = new MyGraphicsView();
connect(m_ui.myView, &MyGraphicsView::mySignal, this, &MyMainWindow::mySlot)
myView and m_ui.myView are not the same object and likely not from the same class.
Hi they are the same, I just removed all the other extra stuff to simplify my problem. In my project, myView was promoted to MyGraphicsView class in the ui instead of declaring it in the main_window.cpp
-
Hi I figured it out.
First I should subclass QGraphicsObject for my item instead of QGraphicsItem, because it was made specifically for use of signal and slots inside graphicsitem.
Then when the item object fired a signal, catch it in the graphicsView object and then forward it to the main_window at the top. Just create a signal with the same name for each of the item and view class.
MyGraphicsItem.cpp
class MyGraphicsItem: public QGraphicsObject { Q_OBJECT ... void myFunction() { emit mySignal(); } }
MyGraphicsView .cpp
class MyGraphicsView : public QGraphicsView { ... scene = new QGraphicsScene(this); myItem = new MyGraphicsItem(); scene->addItem(myItem); connect(myItem, &MyGraphicsItem::mySignal, this, &MyGraphicsView::mySignal); }
main_window.cpp
connect(m_ui.myView, &MyGraphicsView::mySignal, this, &MyMainWindow::mySlot)