C++ (Qt)void Qcr::hoverMoveEvent(QGraphicsSceneHoverEvent* e){ QPainterPath path = shape(); QRect mouseRect( mapToItem(this, e->pos()).x(), mapToItem(this, e->pos()).y(), 1, 1); if( path.intersects( mouseRect ) ) { isHover_ = true; } else { isHover_ = false; } update();}
C++ (Qt)#ifndef WIDGET_H#define WIDGET_H #include <QWidget>#include <QPainterPath> class Widget : public QWidget{ Q_OBJECTpublic: explicit Widget( QWidget *parent = 0 ); protected: virtual void paintEvent( QPaintEvent *ev ) override; virtual void mousePressEvent( QMouseEvent *ev ); private: QPainterPath m_path;}; #endif // WIDGET_H
C++ (Qt)#include "widget.h"#include <QPainter>#include <QMouseEvent>#include <QDebug> Widget::Widget( QWidget *parent ) : QWidget( parent ){ m_path.addEllipse( QRectF( 0, 0, 100, 100 ) );} void Widget::paintEvent( QPaintEvent * ){ QPainter p( this ); p.drawPath( m_path );} void Widget::mousePressEvent( QMouseEvent *ev ){ qDebug() << m_path.contains( ev->pos() );}
C++ (Qt)void Qcr::hoverMoveEvent(QGraphicsSceneHoverEvent* e){ QPainterPath path = shape(); qDebug() << path.contains( e->pos() );}
C++ (Qt)#include "Qcr.h"#include <QDebug> Qcr::Qcr(QGraphicsItem* parent) : QGraphicsObject() , startAngle(0) , sweepLength(0) , isHover_(false){ setAcceptHoverEvents(true); boundingRect_.setX(-50); boundingRect_.setY(-50); boundingRect_.setWidth(100); boundingRect_.setHeight(100);} Qcr::~Qcr(){} void Qcr::paint(QPainter * painter, const QStyleOptionGraphicsItem* option, QWidget * widget /*= 0 */){ QPen myPen; QPointF center, startPoint; if(isHover_) { painter->setBrush(QBrush(QColor(255, 0, 0))); } else { painter->setBrush(QBrush(QColor(0, 255, 0))); } QPainterPath myPath; myPath.moveTo(0,0); myPath.arcTo(boundingRect_, startAngle, sweepLength); myPath.closeSubpath(); painter->setPen(myPen); painter->drawPath(myPath);} void Qcr::hoverMoveEvent(QGraphicsSceneHoverEvent* e){ QPainterPath path = shape(); if( path.contains( e->pos() ) ) { isHover_ = true; } else { isHover_ = false; } update();} void Qcr::hoverLeaveEvent(QGraphicsSceneHoverEvent * event){ isHover_ = false; update();} QRectF Qcr::boundingRect() const{ return boundingRect} void Qcr::setStartAngleX(int x){ startAngle = x; update();} void Qcr::setStartAngleY(int y){ sweepLength = y; update();} void Qcr::setStartAngleW(int w){ qreal oldW = boundingRect_.width(); qreal oldH = boundingRect_.height(); boundingRect_.setX(-w/2); boundingRect_.setWidth(w); boundingRect_.setHeight( qreal(oldW/w) * oldH ); boundingRect_.setY(-boundingRect_.height()/2); update();} void Qcr::setStartAngleH(int h){ boundingRect_.setY(-h/2); boundingRect_.setHeight(h); update();}