要在Qt QGraphicsView中绘制多边形,内部为白色,外部为黑色,请按照以下步骤进行操作:
创建一个新的QGraphicsItem子类,用于表示多边形。
在QGraphicsItem子类中实现paint()函数,在其中使用QPainter来绘制多边形。在这里,您可以使用QPen和QBrush设置颜色和填充样式。
设置多边形项的填充规则为Qt::OddEvenFill,这将使其内部区域被填充,并且不与重叠的区域相交。
下面是示例代码,演示如何在Qt QGraphicsView中绘制多边形,内部为白色,外部为黑色:
#include <QtGui>
class PolygonItem : public QGraphicsItem
{
public:
PolygonItem(QGraphicsItem* parent = nullptr)
: QGraphicsItem(parent)
{
setFlags(ItemIsMovable | ItemIsSelectable);
}
QRectF boundingRect() const override
{
return m_polygon.boundingRect();
}
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override
{
painter->setRenderHint(QPainter::Antialiasing);
QPainterPath path;
path.addPolygon(m_polygon);
path.closeSubpath();
// Fill the polygon with white color
painter->setPen(Qt::NoPen);
painter->setBrush(Qt::white);
painter->drawPath(path);
// Draw black outline around the polygon
painter->setPen(QPen(Qt::black, 2));
painter->setBrush(Qt::NoBrush);
painter->drawPath(path);
}
void addPoint(const QPointF& point)
{
m_polygon << point;
}
private:
QPolygonF m_polygon;
};
class GraphicsView : public QGraphicsView
{
public:
GraphicsView(QWidget* parent = nullptr)
: QGraphicsView(parent)
{
setRenderHint(QPainter::Antialiasing);
setDragMode(RubberBandDrag);
setViewportUpdateMode(FullViewportUpdate);
viewport()->installEventFilter(this);
}
protected:
bool eventFilter(QObject* object, QEvent* event) override
{
if (event->type() == QEvent::MouseButtonPress)
handleMousePressEvent(static_cast<QMouseEvent*>(event));
else if (event->type() == QEvent::MouseMove)
handleMouseMoveEvent(static_cast<QMouseEvent*>(event));
return false;
}
private:
void handleMousePressEvent(QMouseEvent* event)
{
if (event->button() != Qt::LeftButton)
return;
QPointF pos = mapToScene(event->pos());
if (!m_currentItem) {
m_currentItem = new PolygonItem;
scene()->addItem(m_currentItem);
}
m_currentItem->addPoint(pos);
update();
}
void handleMouseMoveEvent(QMouseEvent* event)
{
if (!(event->buttons() & Qt::LeftButton))
return;
QPointF pos = mapToScene(event->pos());
// Connect last point of the current item with mouse position
if (m_currentItem) {
int count = m_currentItem->polygon().count();
if (count > 0) {
QPointF lastPoint = m_currentItem->polygon().at(count - 1);
QLineF line(lastPoint, pos);
// If the line is too short, skip this point
if (line.length() < 5)
return;
m_currentItem->addPoint(pos);
update();
}
}
}
private:
PolygonItem* m_currentItem = nullptr;
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QGraphicsScene scene;
GraphicsView view;
view.setScene(&scene);
view.show();
return app.exec();
}
在这个示例中,我们创建了一个自定义的多边形项类PolygonItem,并在其中实现了paint()函数,用于绘制多边形。我们使用白色笔刷和黑色边框填充多边形。
为了使多边形内部区域被填充,我们设置多边形项的填充规则为Qt::OddEvenFill。这将确保内部区域被正确地填充,并且不与重叠的区域相交。
使用这个示例代码作为起点,您可以进一步扩展它来实现您所需的功能。