我想创建一个自定义文本项,当被选中时,它的边框变为绿色,并且它的文本可以像setTextInteractionFlags(Qt::TextEditorInteraction);
在QGraphicsTextItem类中一样更改,但我想继承QGraphicsItem类并实现类似的东西。我的问题是如何使用覆盖绘制方法在文本项中实现眨眼文本光标?或者换句话说,这种情况的最佳解决方案是什么?
TextItem.h
:
#include "QGraphicsTextItem"
#include "QKeyEvent"
#include "QRectF"
class TextItem : public QGraphicsItem {
public :
TextItem(int x, int y);
QRectF boundingRect() const override;
protected:
void keyPressEvent(QKeyEvent *event) override;
public:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
~TextItem();
private:
QColor color;
int x, y, width, height;
QString text;
void onSelectItem(QPainter *pPainter);
};
和TextItem.cpp
:
#include <iostream>
#include "TextItem.h"
#include "QPainter"
#include "QTextItem"
#include "QKeyEvent"
#include "QStaticText"
#include "QStyleOptionGraphicsItem"
using namespace std;
TextItem::~TextItem() noexcept {}
TextItem::TextItem(int x, int y) : x(x),
y(y),
width(60),
height(60),
text(),
color(Qt::black) {
this->setFlags(ItemIsSelectable | ItemIsFocusable);
}
void TextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
if (this->isSelected()) {
onSelectItem(painter);
// I think it should be draw here
// setTextEditor(painter);
}
painter->save();
painter->setRenderHint(QPainter::TextAntialiasing);
QPen pen(Qt::black);
painter->setPen(pen);
painter->setBrush(color);
painter->drawText(this->boundingRect(), text == "" ? "hello world" : text, QTextOption(Qt::AlignLeft));
painter->restore();
}
void TextItem::keyPressEvent(QKeyEvent *event) {
if (this->isSelected()) {
text += event->text();
this->update();
}
QGraphicsItem::keyPressEvent(event);
}
void TextItem::onSelectItem(QPainter *painter) {
painter->save();
QPen pen(Qt::green);
pen.setJoinStyle(Qt::MiterJoin);
pen.setWidth(2);
painter->setPen(pen);
painter->drawRect(this->boundingRect());
painter->restore();
}
QRectF TextItem::boundingRect() const {
return QRectF(x, y, width, height);
}
我希望我已经正确地表达了我的意思。