QGraphicsViewにおけるイベント処理

昨日のやつに

  • クリックイベント処理
  • ドラッグによる移動

を追加した

#include <QtGui>

class MyPixmapItem : public QGraphicsPixmapItem
{
private:
    bool isDragged;       // ドラッグ中フラグ
    QPoint mpos, wpos;    // ドラッグ開始時点のマウス位置、ウィンドウ位置
    
public:
    MyPixmapItem( const QPixmap &pixmap,
                  QGraphicsItem *parent,
                  QGraphicsScene *scene );    
        
protected:
    void mousePressEvent( QGraphicsSceneMouseEvent *event );
    void mouseMoveEvent( QGraphicsSceneMouseEvent *event );
    void mouseReleaseEvent( QGraphicsSceneMouseEvent *event );    
};

MyPixmapItem::MyPixmapItem( const QPixmap &pixmap,
                            QGraphicsItem *parent = 0,
                            QGraphicsScene *scene = 0 )
    : QGraphicsPixmapItem( pixmap, parent, scene )
{
    this->isDragged = false;
}

void MyPixmapItem::mousePressEvent( QGraphicsSceneMouseEvent *event )
{
    Qt::MouseButton b = event->button();

    if( b == Qt::RightButton )
    {
        qApp->quit();
    }
    else
    {
        this->mpos = event->screenPos();
        this->wpos = qApp->activeWindow()->pos();
        this->isDragged = true;
    }
}

void MyPixmapItem::mouseMoveEvent( QGraphicsSceneMouseEvent *event )
{
    if( this->isDragged )
    {
        QPoint diff = event->screenPos() - this->mpos;
        QPoint newpos = this->wpos + diff;
        
        QWidget *widget = qApp->activeWindow();
        widget->move( newpos );
    }
}

void MyPixmapItem::mouseReleaseEvent( QGraphicsSceneMouseEvent *event )
{
    this->isDragged = false;
}

    
int main( int argc, char *argv[] )
{
    QApplication a( argc, argv );

    // scene, view作成
    QGraphicsScene scene;
    QGraphicsView view( &scene );

    // MyPixmapItem作成
    QPixmap pm( "c:\\afx.png" );
    MyPixmapItem pm1(
        pm.scaled(
            180, 180, Qt::IgnoreAspectRatio, Qt::SmoothTransformation
        )
    );

    // エフェクト作成
    QGraphicsDropShadowEffect* shadow1	= new QGraphicsDropShadowEffect();
    shadow1->setColor( QColor( 0, 0, 0 ) );
    shadow1->setOffset( 5, 5 );
    shadow1->setBlurRadius( 15 );

    // MyPixmapItem配置
    pm1.setGraphicsEffect( shadow1 );
    pm1.setPos( 0, 0 );
    scene.addItem( &pm1 );

    // QGraphicsView表示
    view.setStyleSheet( "background:transparent; border: none;");
    view.setAttribute( Qt::WA_TranslucentBackground );
    view.setWindowFlags( Qt::FramelessWindowHint );
    view.resize( 200, 200 );
    view.show();
    
    return a.exec();
}


Qtでは継承して機能追加するのが普通なんですねー