问题
I have a custom implementation of qGraphicsScene and a custom qGraphicsItem that I click on, but the itemAt function never returns a value, even though I am fairly certain that I'm clicking on the item.
void VScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if ((vMouseClick) && (event->pos() == vLastPoint)) {
QGraphicsItem *mod = itemAt(event->pos(), QTransform());
if (mod) { // Never returns true
// ...
}
}
}
For clarity, the module is added in the following code:
void VScene::addModule(QString modName, QPointF dropPos)
{
VModule *module = new VModule();
addItem(module);
// the QPointF value comes from an event in mainWindow, the coordinate is mapped to my scene.
module->setPos(dropPos);
}
... and here is the custom qGraphicsItem that I have written.
VModule.h:
class VModule : public QObject, public QGraphicsItem
{
public:
explicit VModule();
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
private:
qreal w;
qreal h;
int xAddr;
int yAddr;
QPolygonF baseShape;
}
VModule.cpp:
VModule::VModule()
{
w = 80;
h = 80;
xAddr = w / 2;
yAddr = h / 2;
// Use the numbers to create a number of polygons
QVector<QPointF> basePoints = { QPointF(0.0, 0.0),
QPointF(xAddr, yAddr),
QPointF(0.0, yAddr * 2),
QPointF(-xAddr, yAddr) };
baseShape = QPolygonF(basePoints);
}
QRectF VModule::boundingRect() const
{
return QRectF(-xAddr, 0, w, h);
}
void VModule::paint(QPainter *painter, const QStypeOptionGraphicsItem *option, QWidget *widget)
{
// brushes and so on are set
// ...
painter->drawPolygon(baseShape, qt::OddEvenFill);
// there are other polygons are drawn in the same way as above
}
Are there any problems with my implementation? Is there something I am missing? Thanks in advance for any help.
回答1:
You are querying the scene in item coordinates instead of scene coordinates. Use:
...
QGraphicsItem *mod = itemAt(event->scenePos());
...
来源:https://stackoverflow.com/questions/16919819/itemat-not-returning-custom-qgraphicsitem