qgraphicsitem 复制副本,QGraphicsTextItem编辑需要执行两次操作

在Qt应用中,创建了一个QGraphicsTextItem,期望通过双击使其变为可编辑,并在失去焦点时变为不可编辑。然而,实际操作中需要双击两次才能开始编辑。解决方案是在mouseDoubleClickEvent中调用setFocus(),使得第一次双击即可开始编辑。
摘要由CSDN通过智能技术生成

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

#include

#include

#include

#include

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 ?

解决方案

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值