DiagramDesigner/diagramCavas/source/graphicsItem/handleText.cpp

83 lines
2.1 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "graphicsItem/handleText.h"
#include <QPainter>
#include <QLineEdit>
#include <QGraphicsProxyWidget>
HandleText::HandleText(QGraphicsItem *parent)
: ItemControlHandle(parent)
,_font(QFont())
,_proxy(nullptr)
,_nIndex(-1)
,_type(0)
{
_editable = true;
_boundingRect = QRectF(-TEXT_WIDTH*0.5,-TEXT_WIDTH*0.5,TEXT_WIDTH,TEXT_HEIGHT);
}
HandleText::~HandleText()
{
}
void HandleText::setText(QString str)
{
_text = str;
QFontMetrics fontMetrics(_font);
_boundingRect = fontMetrics.boundingRect(_text);
int w = _boundingRect.width();
int h = _boundingRect.height();
_boundingRect.moveTo(QPointF(-w*0.5,-h*0.5));
}
QString HandleText::getText() const
{
return _text;
}
void HandleText::creatEditor()
{
if(!_editable)
return;
if(!_proxy)
_proxy = new QGraphicsProxyWidget(this);
_proxy->setVisible(true);
QLineEdit *editor = new QLineEdit();
editor->setText(_text);
editor->resize(boundingRect().size().toSize()*1.5);
_proxy->setWidget(editor);
// 将文本编辑的更改连接到文本项
connect(editor, &QLineEdit::textChanged, this, [this, editor]() {
//_text = editor->text();
setText(editor->text());
});
// 完成编辑后删除QTextEdit
connect(editor, &QLineEdit::editingFinished, this, [this, editor]() {
//_text = editor->text();
setText(editor->text());
emit editFinish(editor->text());
_proxy->setVisible(false);
});
}
void HandleText::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
painter->setPen(Qt::blue);
painter->setBrush(Qt::blue);
painter->setRenderHint(QPainter::TextAntialiasing, true);
int w = _boundingRect.width();
int h = _boundingRect.height();
if(_type == 0)
painter->drawText(QPointF(-w*0.5,h*0.5),_text);
else{
QString displayText = _sTagName + ":" + _text;
painter->drawText(boundingRect(), Qt::AlignCenter, displayText);
}
}
QRectF HandleText::boundingRect() const
{
return _boundingRect;
}