QGraphicsTextItem编辑需要执行两次操作 [英] QGraphicsTextItem editing requires an action performed twice

查看:3180
本文介绍了QGraphicsTextItem编辑需要执行两次操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个 QGraphicsTextItem 在双击时可编辑,并在我点击后移动。

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

它会做我想要的 - 除非我必须双击两次

- 第一次双击,我看到一个光标,但无法编辑文本(使用 TextEditable TextEditorInteraction (我可能想要后者)然后我再次双击,我可以键入以添加或删除文本。

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.

我做错了什么,还是有什么我需要添加?

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

推荐答案

我希望对可调焦项目进行鼠标操作,以自动给予焦点,我猜...

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

mouseDoubleClickEvent 中,我添加了对 setFocus()

virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
    Q_UNUSED(event);
    setTextInteractionFlags(Qt::TextEditorInteraction); 
    setFocus();
}

这篇关于QGraphicsTextItem编辑需要执行两次操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆