简体   繁体   中英

QGraphicsPixmapItem - trigger only event of the top object

I am trying to make a card game. The player has vector of Cards and(hand) which is represtend in GUI.

示例它的外观

My cards inherits from QGraphicsPixmapItem and QObject. What I want to achieve is to set MouseEvent on Card and trigger this event only for one single card. Now there is a problem if I click on Card, there are situation whey ther are close(like in the picture) and event occurs on more than one card.

How can I preventing my Cards from this behaviour?

Here's my Card.cpp (with sceneEvent method)

#include "Card.h"
#include "Game.h"
#include <string>
#include <QDebug>
#include <QPixmap>
#include <QSize>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QEvent>

extern Game * game;

Card::Card(QString pixmapURL, std::string rank, std::string suit, int value)
{
    this->pixmapURL = pixmapURL;
    this->rank = rank;
    this->suit = suit;
    this->value = value;

    setPixmap(QPixmap(this->pixmapURL));
    setScale(0.10);
}

int Card::getValue()
{
    return this->value;
}

std::string Card::getSuit()
{
    return this->suit;
}

std::string Card::getRank()
{
    return this->rank;
}

void Card::display()
{
    qDebug() << this->suit.c_str() << this->rank.c_str();
}

bool Card::sceneEvent(QEvent *event)
{
    if (event->type() == QEvent::GraphicsSceneMousePress) {
        //qDebug() << event->MouseButtonPress;
        setPos(game->scene->width()/2, game->scene->height()/2);
    }
    return QGraphicsItem::sceneEvent(event);
}

You need to accept the event for that object.

From QEvent documentation:

Setting the accept parameter indicates that the event receiver wants the event. Unwanted events might be propagated to the parent widget.

bool Card::sceneEvent(QEvent *event)
{
    if (event->type() == QEvent::GraphicsSceneMousePress) {
        //qDebug() << event->MouseButtonPress;
        event->setAccepted(true); // this will prevent the event from being propagated to underlaying objects
        setPos(game->scene->width()/2, game->scene->height()/2);
    }
    return QGraphicsItem::sceneEvent(event);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM