Search code examples
qtqgraphicsviewqgraphicstextitem

How to remove the focus of a QGraphicsTextItem from a main QWidget


I have a number of QGraphicsTextItem and QGraphicsItem painted inside a QGraphicsView. This QGraphicsView has been added to the main Qwidget.

I have written the "FocusOutEvent" for this QGraphicsTextItem and the focus is getting removed only when the "MousePressEvent" is called within the QGraphicsView.

Now my concern here is, How to remove the focus of this QGraphicsTextItem when the MousePressEvent is called Outside the QGraphicsView?

In my MainWindow.cpp, I wrote a mousePressEvent function :

void EyGuiMainWindow::mousePressEvent(QMouseEvent *e)
{
  QWidget *w = QApplication::focusWidget();
  if(w)
     w->clearFocus();
}

But this is not clearing the QGraphicsTextItem.

Expecting a positive response.


Solution

  • A QGraphicsTextItem is not a widget, but a QGraphicsItem. Graphics items are added to a QGraphicsScene and viewed by one or more QGraphicsView widgets.

    The code presented is only calling clear focus on the currently focussed widget, but since the QGraphicsTextItem is not a widget, it won't be cleared.

    In order to clear the focus on the QGraphicsTextItem, call its clearFocus function. If you don't have a pointer to the item, you can get a list of all the items in the scene with the items() function and iterate through them.