覆盖QGraphicsItem的paint()和mouseEvents()

时间:2015-10-14 14:05:03

标签: c++ qt

在Qt中,我正在尝试突出显示一个项目,当我点击它然后从其末端绘制一条线到当前光标位置。我可以突出显示它或绘制线条,但不能同时绘制线条。这是我的课程:

// ucPin.h 
#pragma once
#include "stdafx.h"

class ucPin : public QGraphicsLineItem{
    qreal x1, y1, x2, y2;
    bool isClicked;
    QGraphicsLineItem * li;
public : 

    ucPin (qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent = 0);

    void paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget );
    void mousePressEvent    (QGraphicsSceneMouseEvent * event);
    void mouseReleaseEvent  (QGraphicsSceneMouseEvent *event);
    void mouseMoveEvent     (QGraphicsSceneMouseEvent *event);

};

// ucPin.cpp
    #include "ucPin.h"

ucPin::ucPin (qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent) : 
        QGraphicsLineItem(x1, y1, x2, y2, parent){
        this->x1 = x1; this->y1 = y1; this->x2 = x2; this->y2 = y2;
        this->setFlags(QGraphicsItem::ItemIsFocusable
                | QGraphicsItem::ItemIsSelectable);

        isClicked = false;
        li = NULL;
    }

void ucPin::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget )
{  

    QStyleOptionGraphicsItem newOption  (*option);
    newOption.state =QStyle::State_None;
    QGraphicsLineItem::paint(painter, &newOption, widget);

    //painter-> setRenderHint(QPainter::Antialiasing);


    if (option->state & QStyle::State_Selected) {
        QPen outline;
        outline.setColor(Qt::green);
        outline.setWidth(6);
        setPen(outline);
    }
    else{
        QPen outline; outline.setWidth(3);
        setPen(outline);
    }
}

void ucPin::mousePressEvent(QGraphicsSceneMouseEvent* event) {
    /*QPointF pos = event->pos();

    QGraphicsLineItem * li = new QGraphicsLineItem(0,0, pos.x(), pos.y(), this);*/
    isClicked = true;
}

void ucPin::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) {
    isClicked = false;
}

void ucPin::mouseMoveEvent(QGraphicsSceneMouseEvent* event) {
    if(NULL != li)  { delete li; li = NULL;}

    li = new QGraphicsLineItem(0,0, event->pos().x(), event->pos().y(), this);

}

我想在实现mouseEvent覆盖时,不会调用所选状态的paint事件?如何解决这个问题呢?

1 个答案:

答案 0 :(得分:1)

要请求重新绘制QGraphicsItem,您需要在外观发生变化时致电update()setSelected在QGraphicsItem :: mousePressEvent中调用,因此您需要将其传播到覆盖QGraphicsLineItem::mousePressEvent(event)中调用mousePressEvent的基类。同样适用于mouseReleaseEvent。或者您可以自己处理选择状态,但除非有充分的理由,否则您不应该这样做。另外,我认为在调用QGraphicsLineItem::paint(...)之前设置笔可能是有意义的。

此外,每次鼠标移动时分配新的li效率很低 - 只需分配一次并使用setLine设置新坐标。