自定义图形(矩形)
// 自定义 Item
RectangleItem::RectangleItem(QGraphicsItem *parent)
: QGraphicsRectItem(parent)
{
// 画笔 - 边框色
p = pen();
p.setWidth(1);
p.setColor(CGlobal:: DRAW_COLOUR_JXBORDER);
setPen(p);
// 画刷 - 背景色
setBrush(CGlobal:: DRAW_COLOUR_JX);
// 可选择
setFlags(QGraphicsItem::ItemIsSelectable);
font.setPointSize(10); //字体大小
font.setBold(false); //字体加粗
font.setFamily("Microsoft YaHei"); //设置字体样式
textItem = new QGraphicsTextItem(this);
}
矩形添加文字
//给矩形添加文字 调用此方法
void RectangleItem::addTextItem(QString text){
textItem->setPlainText(text);
textItem->setTextWidth(this->boundingRect().width()); //设置编辑框宽度
textItem->setDefaultTextColor(CGlobal:: DRAW_COLOUR_FONT); //设置字体颜色
//qDebug()<<this->boundingRect().width();
//文字居中
QTextBlockFormat format;
format.setAlignment(Qt::AlignCenter); //设置字体居中
QTextCursor cursor = textItem->textCursor();
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(format);
cursor.clearSelection();
textItem->setTextCursor(cursor);
//设置item放置位置
//QPointF p =this->boundingRect().center();
QPointF pos(this->boundingRect().x(),this->boundingRect().center().ry()-15);
textItem->setPos(pos);
textItem->setFont(font);
}
添加设置矩形的圆角以及去除焦点选中外边线
当自定继承了QGraphicsRectItem类,则不能直接使用drawRoundedRect方法,因此定义不了圆角。
需重新paint方法。矩形选中时会出现外边虚线,可进行自定义外边虚线样式。
void RectangleItem:: paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
QStyleOptionGraphicsItem op;
op.initFrom(widget);
// 判断选中时,设置状态为 State_None
if (option->state & QStyle::State_Selected)
op.state = QStyle::State_None;
// 调用默认方法,进行原始绘制
//QGraphicsRectItem::paint(painter, &op, widget);
painter->setPen(p); //边框色
painter->setBrush(this->brush());
painter->drawRoundedRect(this->rect(), 2, 2); //圆角5像素
// 选中时绘制
if (option->state & QStyle::State_Selected) {
qreal itemPenWidth = pen().widthF();
const qreal pad = itemPenWidth / 2;
const qreal penWidth = 2;
// 边框区域颜色
QColor color = QColor(CGlobal:: DRAW_JX_XZ);
// 绘制实线
painter->setPen(QPen(color, penWidth, Qt::SolidLine));
painter->setBrush(Qt::NoBrush);
painter->drawRoundedRect(boundingRect().adjusted(pad, pad, -pad, -pad), 2, 2);
// 绘制虚线
// painter->setPen(QPen(color, 0, Qt::DashLine));
// painter->setBrush(Qt::NoBrush);
// painter->drawRect(boundingRect().adjusted(pad, pad, -pad, -pad));
}
}
给图形添加阴影
在设置阴影时,不能在自定的图形类中调用setGraphicsEffect方法,需要在获取到图形对象,如下设置即可
//添加阴影
QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
shadow_effect->setOffset(0, 0); //阴影偏移
shadow_effect->setColor(Qt::black); //隐隐颜色
shadow_effect->setBlurRadius(20); //阴影半径
item->setGraphicsEffect(shadow_effect); //给item设置阴影
item->setGraphicsEffect(NULL); //去除item设置阴影
版权声明:本文为weixin_43525290原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。