#include "CTextItem.h" #include #include #include #include #include #include #include CTextItem::CTextItem(QGraphicsItem *parent) : CTextItem(QString(), parent) { } CTextItem::CTextItem(const QString &text, QGraphicsItem *parent) : QGraphicsTextItem(text, parent) { setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable); setTextInteractionFlags(Qt::TextEditorInteraction); connect(document(), &QTextDocument::contentsChanged, this, &CTextItem::slotTextChanged); connect(document(), &QTextDocument::contentsChange, this, &CTextItem::slotTextChange); } void CTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton) { //左键双击进入可编辑状态并打开焦点 if (allowEdit()) { emit sigWillBeginEditing(); beginEditing(); } QGraphicsTextItem::mouseDoubleClickEvent(event); } } void CTextItem::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Return: { endEditing(); } } QGraphicsTextItem::keyPressEvent(event); } void CTextItem::beginEditing() { setTextInteractionFlags(Qt::TextEditorInteraction); setFocus(); parentItem()->setZValue(-1); } void CTextItem::endEditing() { setZValue(0); setTextInteractionFlags(Qt::NoTextInteraction); setSelected(false); clearFocus(); if (m_textChanged) { emit sigTextChanged(); m_textChanged = false; } // 没找到取消文字选中状态的方法, 暂且用这个吧 // 因为这相当于编辑了文字, 会触发数据库保存操作 setPlainText(toPlainText()); } bool CTextItem::isEditing() const { return (textInteractionFlags() & Qt::TextEditorInteraction) == Qt::TextEditorInteraction; } bool CTextItem::allowEdit() const { return m_allowEdit; } void CTextItem::setAllowEdit(bool a) { m_allowEdit = a; if (a == false) { endEditing(); } } QSizeF CTextItem::textSize(const QString t, qreal width) { static CTextItem *i = nullptr; if (i == nullptr) { i = new CTextItem(nullptr); } i->document()->setPlainText(t); i->setTextWidth(width); return i->document()->size(); } void CTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QGraphicsTextItem::paint(painter, option, widget); } void CTextItem::slotTextChanged() { m_textChanged = true; } void CTextItem::slotTextChange(int from, int charsRemoved, int charsAdded) { Q_UNUSED(from) Q_UNUSED(charsRemoved) Q_UNUSED(charsAdded) QTextCursor c = textCursor(); if (toPlainText().contains(" ")) { setPlainText(toPlainText().remove(QRegExp("\\s"))); setTextCursor(c); } }