【问题标题】:QGraphicsPixmapItem - trigger only event of the top objectQGraphicsPixmapItem - 仅触发顶部对象的事件
【发布时间】:2019-10-30 15:16:48
【问题描述】:

我正在尝试制作纸牌游戏。玩家有卡片和(手)的向量,它在 GUI 中表示。

我的卡片继承自 QGraphicsPixmapItem 和 QObject。 我想要实现的是在 Card 上设置 MouseEvent 并仅为一张卡触发此事件。现在如果我点击卡片就会出现问题,出现关闭的情况(如图所示)并且事件发生在多张卡片上。

如何防止我的卡出现这种行为?

这是我的 Card.cpp(使用 sceneEvent 方法)

#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);
}

【问题讨论】:

    标签: c++ qt qgraphicspixmapitem


    【解决方案1】:

    您需要accept 该对象的事件。

    来自QEvent 文档:

    设置accept参数表示事件接收者想要 事件。不需要的事件可能会传播到父小部件。

    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);
    }
    

    【讨论】:

    • 但我想点击每张卡片。我只想为每个 MousePress 触发一张卡的事件
    • 更新了我的答案:event-&gt;setAccepted(true);
    • 触发不止一张卡
    猜你喜欢
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多