如何在不按QGraphicsScene中的Ctrl键的情况下选择多个项目?

时间:2010-09-28 06:34:45

标签: qt qgraphicsview

在Qt的QGraphicsScene中,如果我想要一个项目,只需单击它,然后单击另一个可选项目将使所选项目取消选中。如果我想选择多个项目,我会使用Ctrl键。但是在某些情况下这可能不方便,那么如何在QGraphicsScene内不按Ctrl键来选择多个项目?

2 个答案:

答案 0 :(得分:8)

您想要更改QGraphicsScene的默认行为,因此您必须创建自己的场景类,继承QGraphicsScene

在课堂上,您必须至少重新实现mousePressEvent并自行处理项目选择。

您可以这样做(继承的场景类称为GraphicsSelectionScene):

void GraphicsSelectionScene::mousePressEvent(QGraphicsSceneMouseEvent* pMouseEvent) {
    QGraphicsItem* pItemUnderMouse = itemAt(pMouseEvent->scenePos().x(), pMouseEvent->scenePos().y());

    if (!pItemUnderMouse)
        return;
    if (pItemUnderMouse->isEnabled() &&
        pItemUnderMouse->flags() & QGraphicsItem::ItemIsSelectable)
        pItemUnderMouse->setSelected(!pItemUnderMouse->isSelected());
}

以这种方式实施,点击一个项目,如果它已经选择了它,否则将取消选择它。

但是要小心,实现mousePressEvent肯定是不够的:如果你不想要默认行为,你还必须处理mouseDoubleClickEvent

您的场景必须由QGraphicsView显示。以下是创建自己场景的视图示例(MainFrm类继承QGraphicsView):

#include "mainfrm.h"
#include "ui_mainfrm.h"
#include "graphicsselectionscene.h"
#include <QGraphicsItem>

MainFrm::MainFrm(QWidget *parent) : QGraphicsView(parent), ui(new Ui::MainFrm) {
    ui->setupUi(this);

    // Create a scene with our own selection behavior
    QGraphicsScene* pScene = new GraphicsSelectionScene(this);
    this->setScene(pScene);

    // Create a few items for testing
    QGraphicsItem* pRect1 = pScene->addRect(10,10,50,50, QColor(Qt::red), QBrush(Qt::blue));
    QGraphicsItem* pRect2 = pScene->addRect(100,-10,50,50);
    QGraphicsItem* pRect3 = pScene->addRect(-200,-30,50,50);

    // Make sure the items are selectable
    pRect1->setFlag(QGraphicsItem::ItemIsSelectable, true);
    pRect2->setFlag(QGraphicsItem::ItemIsSelectable, true);
    pRect3->setFlag(QGraphicsItem::ItemIsSelectable, true);
}

答案 1 :(得分:1)

也许这是一个黑客但它对我有用。在此示例中,您可以使用shift键选择多个项目

void MySceneView::mousePressEvent(QMouseEvent *event)
{
    if (event->modifiers() & Qt::ShiftModifier ) //any other condition
        event->setModifiers(Qt::ControlModifier);

    QGraphicsView::mousePressEvent(event);
}


void MySceneView::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->modifiers() & Qt::ShiftModifier ) //any other condition
        event->setModifiers(Qt::ControlModifier);

    QGraphicsView::mouseReleaseEvent(event);
}