用Qt的GraphicsItem 自绘一个QLinedit
时间: 2024-05-12 17:19:44 浏览: 206
Qt自绘控件
5星 · 资源好评率100%
以下是一个使用Qt的GraphicsItem自绘QLinedit的示例代码:
```cpp
#include <QGraphicsItem>
#include <QPainter>
#include <QLineEdit>
class CustomLineEdit : public QGraphicsItem
{
public:
CustomLineEdit(QGraphicsItem *parent = nullptr)
: QGraphicsItem(parent)
{
m_lineEdit.setParent(nullptr);
m_lineEdit.installEventFilter(this);
}
QRectF boundingRect() const override
{
return QRectF(0, 0, 100, 20);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
Q_UNUSED(option)
Q_UNUSED(widget)
painter->setPen(Qt::black);
painter->drawRect(boundingRect());
QRectF textRect = boundingRect().adjusted(2, 2, -2, -2);
painter->setFont(m_lineEdit.font());
painter->drawText(textRect, m_lineEdit.text());
}
bool eventFilter(QObject *obj, QEvent *event) override
{
if (obj == &m_lineEdit && event->type() == QEvent::TextEdited)
{
update();
return true;
}
return false;
}
private:
QLineEdit m_lineEdit;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QGraphicsScene scene;
CustomLineEdit *customLineEdit = new CustomLineEdit();
scene.addItem(customLineEdit);
customLineEdit->setPos(20, 20);
QGraphicsView view(&scene);
view.show();
return app.exec();
}
```
在这个示例中,我们创建了一个名为CustomLineEdit的自定义GraphicsItem,它继承自QGraphicsItem。在CustomLineEdit的构造函数中,我们创建了一个QLineEdit,并使用eventFilter来捕获TextEdit的文本编辑事件,并在其上绘制文本。在paint函数中,我们使用QPainter来绘制一个矩形和文本。CustomLineEdit的boundingRect函数返回矩形的大小。最后,我们将CustomLineEdit添加到QGraphicsScene中并在QGraphicsView中显示它。
阅读全文