QGraphicsItemText won't detect mouse flags
-
04-06-2021 - |
Question
What I'm trying to do is pretty simple, when the mouse is over the qgraphicsitem I want it to change it's text value. Later on I want to use this to pop-up text when I click an image (i.e. the info of the image)
Here's my code so far:
#include <QtGui/QApplication>
#include <QtGui/QGraphicsItem>
#include <QtGui/QGraphicsTextItem>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsView>
#include <QtGui/QPixmap>
int main( int argc, char * * argv )
{
QApplication app( argc, argv );
QGraphicsScene scene;
QGraphicsView view( &scene );
QGraphicsTextItem text( "this is my text");
scene.addItem(&text);
scene.setActivePanel(&text);
text.setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsFocusable);
text.setAcceptHoverEvents(true);
text.setAcceptTouchEvents(true);
if (text.isUnderMouse() || text.isSelected()){
text.setPlainText("test");
}
view.show();
return( app.exec() );
}
Some people use double-click events but I was hoping not to use them, but... if that's the only way to get the job done then it's ok.
Solution
This code block:
if (text.isUnderMouse() || text.isSelected()){
text.setPlainText("test");
}
is run exactly once, before your view is even shown; so this has absolutely no chance of doing what you expect it to.
You'll need to do a bit more work for that, namely create a custom subclass of QGraphicsTextItem
and override the appropriate event handlers.
Here's how you could do that to handle changing text when hovering:
class MyTextItem: public QGraphicsTextItem
{
public:
MyTextItem(QString const& normal, QString const& hover,
QGraphicsItem *parent=0)
: QGraphicsTextItem(normal, parent), normal(normal), hover(hover)
{
}
protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent *)
{
setPlainText(hover);
}
void hoverLeaveEvent(QGraphicsSceneHoverEvent *)
{
setPlainText(normal);
}
private:
QString normal, hover;
};
Add that to your code, and change the text
declaration to:
MyTextItem text("this is my text", "test");
and it should do what you expect.