Qt文档阅读笔记-QGraphicsItem::paint中QStyleOptionGraphicsItem *option的进一步认识
官方解析
painter : 此参数用于绘图;
option : 提供了item的风格,比如item的状态,曝光度以及详细的信息;
widget : 想画到哪个widget上,如果要画在缓存区上,这个参数一般填0;
博主例子
运行截图如下:
源码如下:
mygraphicsitem.h
#ifndef MYGRAPHICSITEM_H
#define MYGRAPHICSITEM_H
#include <QGraphicsItem>
class MyGraphicsItem : public QGraphicsItem
{
public:
MyGraphicsItem(QGraphicsItem *parent = 0);
protected:
QRectF boundingRect() const Q_DECL_OVERRIDE;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) Q_DECL_OVERRIDE;
private:
int m_width;
int m_height;
};
#endif // MYGRAPHICSITEM_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
mygraphicsitem.cpp
#include "mygraphicsitem.h"
#include <QPainter>
#include <QStyleOptionGraphicsItem>
MyGraphicsItem::MyGraphicsItem(QGraphicsItem *parent)
:QGraphicsItem(parent)
{
m_width = 100;
m_height = 100;
}
QRectF MyGraphicsItem::boundingRect() const
{
qreal penWidth = 1;
return QRectF(0-penWidth/2, 0-penWidth/2, m_width+penWidth, m_height+penWidth);
}
void MyGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(widget)
painter->save();
if(option->state & QStyle::State_Selected){
painter->setPen(QPen(Qt::blue, 5));
}
else{
painter->setPen(QPen(Qt::red,5));
}
painter->drawRect(0, 0, m_width, m_height);
painter->restore();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "mygraphicsitem.h"
#include <QGraphicsScene>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
ui->graphicsView->setScene(new QGraphicsScene);
MyGraphicsItem *item = new MyGraphicsItem;
ui->graphicsView->scene()->addItem(item);
item->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
}
Widget::~Widget()
{
delete ui;
}
---------------------
原文:https://blog.csdn.net/qq78442761/article/details/83268088