QtQGraphicsScene
では、1つのアイテムが必要な場合は、それをクリックして、別の選択可能なアイテムをクリックすると、選択したアイテムが選択解除されます。複数の項目を選択したい場合は、Ctrlキーを使用します。しかし、これは場合によっては便利ではないかもしれません。それでは、Ctrlキーを押しずに複数のアイテムを選択するにはどうすればよいQGraphicsScene
ですか?
8338 次
2 に答える
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);
}
于 2010-10-01T12:28:31.350 に答える
2
多分それはハックですが、私にとってはうまくいきます。この例では、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);
}
于 2013-10-03T15:02:58.300 に答える