qgraphicsitem选中出现边框可以拉伸的代码例程
时间: 2023-09-08 08:01:21 浏览: 147
QGraphicsItem选中后,出现边框,可以拉伸
3星 · 编辑精心推荐
QGraphicsItem是Qt中的一个重要的图形项类,用于在QGraphicsScene中显示图形元素。要实现选中QGraphicsItem后出现可拉伸的边框,可以通过以下代码示例实现:
```cpp
#include <QGraphicsItem>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QKeyEvent>
class ResizableItem : public QGraphicsItem
{
public:
ResizableItem(QGraphicsItem *parent = nullptr) : QGraphicsItem(parent),
m_isSelected(false), m_borderColor(Qt::red), m_borderWidth(2), m_resizeHandleSize(6)
{
setFlags(QGraphicsItem::ItemIsSelectable);
}
QRectF boundingRect() const override
{
return QRectF(0, 0, 100, 100);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setRenderHint(QPainter::Antialiasing);
// 绘制选中时的边框
if (m_isSelected) {
painter->setPen(QPen(m_borderColor, m_borderWidth));
painter->setBrush(Qt::NoBrush);
painter->drawRoundedRect(boundingRect(), 5, 5);
// 绘制调整大小的手柄
painter->setBrush(Qt::SolidPattern);
painter->setPen(Qt::NoPen);
painter->drawRect(boundingRect().topRight().x() - m_resizeHandleSize / 2,
boundingRect().topRight().y() - m_resizeHandleSize / 2,
m_resizeHandleSize, m_resizeHandleSize);
}
// 绘制图形元素内容
painter->setPen(Qt::black);
painter->setBrush(QColor(192, 192, 192));
painter->drawRoundedRect(0, 0, 100, 100, 5, 5);
}
void setSelected(bool selected)
{
m_isSelected = selected;
update();
}
protected:
void keyPressEvent(QKeyEvent *event) override
{
if (event->key() == Qt::Key_Delete) {
scene()->removeItem(this);
delete this;
}
}
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
{
// 仅在点击图形元素时选中
if (event->button() == Qt::LeftButton) {
setSelected(true);
event->accept();
} else {
setSelected(false);
event->ignore();
}
}
private:
bool m_isSelected;
QColor m_borderColor;
int m_borderWidth;
int m_resizeHandleSize;
};
```
以上示例代码定义了一个基于QGraphicsItem的可拉伸项(ResizableItem),并重写了paint()函数以绘制图形和选中边框,重写了mousePressEvent()函数以实现点击图形元素时选中的功能,以及重写了keyPressEvent()函数以实现删除选中项的功能。
你可以将这段代码插入进自己的Qt项目中,然后在场景中添加ResizableItem即可实现选中时出现可拉伸的边框的效果。
阅读全文