QGraphicsTextItem editing requires an action performed twice

混江龙づ霸主 提交于 2019-12-13 01:56:57

问题


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:


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();
}


来源:https://stackoverflow.com/questions/31171569/qgraphicstextitem-editing-requires-an-action-performed-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!