开发者

mousePressEvent not binding correctly?

To familiarize myself with Qt's graphics view, I'm implementing a simple chess board in Qt. There are no chess pieces, for now.

I use rectangles to represent every tile, so I made the BoardTile class (which inherits from QGraphicsRectItem) so that I can define a mousePressEvent.

Here's a little test code that I associated with the mouse click:

void BoardTile::mousePressEvent(QGraphicsSceneMouseEvent *event) {
    QMessageBox mesg;
    std::stringstream mesgText;
    mesgText << "Clicked tile (" << this->row_id << ", " << this->col_id << ").";
    mesg.setText(QString::fromStdString(mesgText.str()));
    mesg.exec();
}

When I click the first tile on the second row, I get the following message:

Clicked tile (1, 0)

Then, when I click any other tile, I get the exact same message. The contents of the message depends on whichever tile I clicked first. Why is this? Did I bind the mousePressEvent incorrectly?

Full code http://www.box.net/shared/4m6nrvuxa4 (update 1)

Update 2: I noticed that if I put event->ignore(); after mesg.exec(), it works fine. I know it's not a solution (because it will 开发者_运维问答probably lead to all kinds of weird behavior), but I do wanna know why that does work. Does this reveal anything crucial about any possible mistakes I've made in my implementation?

Update 3: Someone told me I should try changing mousePressEvent to mouseReleaseEvent. Oddly enough, that works. As far as I know, the only difference between the two events is that the first is triggered when you press the mouse button and the latter when you release that button. So why does mouseReleaseEvent trigger the desired behavior and mousePressEvent doesn't?


When you are doing this->x_id you are getting the x position of the RECT, not your mouse click. You have to do event->::pos() taken from the event. The docs are here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜