用Qt的GraphicsItem 自绘一个QLinedit 并且可以输入文本
时间: 2024-05-08 08:16:07 浏览: 224
Qt自绘控件
5星 · 资源好评率100%
以下是一个用Qt的GraphicsItem自绘的QLinedit并且可以输入文本的示例代码:
```
#include <QGraphicsItem>
#include <QPainter>
#include <QLineEdit>
class CustomLineEdit : public QGraphicsItem
{
public:
CustomLineEdit(QGraphicsItem *parent = nullptr)
: QGraphicsItem(parent)
{
setFlag(ItemIsFocusable);
setAcceptHoverEvents(true);
m_edit = new QLineEdit();
m_edit->setFrame(false);
m_edit->setAttribute(Qt::WA_TranslucentBackground);
m_edit->setStyleSheet("QLineEdit { background-color: transparent; }");
m_edit->setAlignment(Qt::AlignCenter);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override
{
Q_UNUSED(option);
Q_UNUSED(widget);
QRectF rect = boundingRect();
painter->setPen(Qt::NoPen);
painter->setBrush(Qt::white);
painter->drawRect(rect);
painter->setPen(Qt::black);
painter->drawText(rect, Qt::AlignCenter, m_edit->text());
}
QRectF boundingRect() const override
{
return QRectF(0, 0, 100, 20);
}
void keyPressEvent(QKeyEvent *event) override
{
if (event->key() == Qt::Key_Backspace)
{
QString text = m_edit->text();
if (!text.isEmpty())
{
text.chop(1);
m_edit->setText(text);
update();
}
}
else
{
m_edit->keyPressEvent(event);
update();
}
}
void focusInEvent(QFocusEvent *event) override
{
m_edit->setFocus();
update();
}
void focusOutEvent(QFocusEvent *event) override
{
m_edit->clearFocus();
update();
}
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override
{
setCursor(Qt::IBeamCursor);
update();
}
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override
{
unsetCursor();
update();
}
private:
QLineEdit *m_edit;
};
```
这里我们定义了一个CustomLineEdit类,继承自QGraphicsItem,然后在paint()函数中绘制了一个白色的矩形和黑色的文本,文本内容是从QLineEdit中获取的。在keyPressEvent()函数中,我们监听了键盘事件,如果是退格键,则从QLineEdit中删除最后一个字符,如果是其他键,则将事件传递给QLineEdit处理。在focusInEvent()和focusOutEvent()函数中,我们将焦点转移到QLineEdit上,以便能够输入文本。在hoverEnterEvent()和hoverLeaveEvent()函数中,我们设置了鼠标悬停时的光标形状。
阅读全文