QGraphicsTextItem editing requires an action perfo

2019-08-08 14:28发布

I want to make a QGraphicsTextItem editable on double click, and make it movable when I click out.

#include <QApplication>
#include <QPainter>
#include <QGraphicsItem>
#include <QGraphicsView>

class TextItem: public QGraphicsTextItem
{
public:
    TextItem()
    {
        setPlainText("hello world");
        QFont f;
        f.setPointSize(50);
        f.setBold(true);
        f.setFamily("Helvetica");
        setFont(f);

        setFlags(QGraphicsItem::ItemIsMovable    |
                 QGraphicsItem::ItemIsFocusable  |
                 QGraphicsItem::ItemIsSelectable);
        setTextInteractionFlags(Qt::NoTextInteraction);
    }
    virtual void paint(QPainter* painter,
                       const QStyleOptionGraphicsItem* option,
                       QWidget* widget = NULL)
    {
        QGraphicsTextItem::paint(painter, option, widget);
    }

protected:
    virtual void focusOutEvent (QFocusEvent * event)
    {
        Q_UNUSED(event);
        setTextInteractionFlags(Qt::NoTextInteraction);
    }
    virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
    {
        Q_UNUSED(event);
        setTextInteractionFlags(Qt::TextEditable); // TextEditorInteraction
    }
};

int main(int argc, char *argv[])
{
    QApplication  a(argc, argv);
    TextItem* t = new TextItem();
    QGraphicsView view(new QGraphicsScene(-200, -150, 400, 300) );
    view.scene()->addItem(t);
    view.show();
    return a.exec();
}

It does what I want - except I have to double-click twice
- first time I double click, I see a cursor but am unable to edit text (with either option, TextEditable or TextEditorInteraction (I probably want the latter). Then I double-click again and I can type to add or delete text.

It is a behavior that a user probably doesn't expect - and nothing I do seems to change it.

Am I doing something wrong, or is there anything I need to add ?

1条回答
孤傲高冷的网名
2楼-- · 2019-08-08 14:57

I expected a mouse action on a focusable item to give it focus automatically. I guess not...

In the mouseDoubleClickEvent, I added a call to setFocus()

virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
    Q_UNUSED(event);
    setTextInteractionFlags(Qt::TextEditorInteraction); 
    setFocus();
}
查看更多
登录 后发表回答