如果传递到QGraphicsRectItem Qt c++,请更改光标

Change the cursor if you pass to a QGraphicsRectItem Qt c++

本文关键字:光标 c++ Qt QGraphicsRectItem 如果      更新时间:2023-10-16

如果经过QGraphicsRectItem这样的矩形,我想更改光标。

我有一个继承自QGraphicsView的类,矩形显示在QGraphicScene中。

我用eventFilter实现了鼠标事件。

问题是,当我已经点击矩形时,光标会发生变化,而我希望它在经过它时发生变化。我已经用QAbstractButton更改了光标,但QGraphicsRectItem::enterEvent(event)不起作用。

这是我的QAbstractButton:代码

void ToggleButton::enterEvent(QEvent *event) {
setCursor(Qt::PointingHandCursor);
QAbstractButton::enterEvent(event);
}

在这种情况下,它是有效的。

这是我用来检测是否通过矩形的代码:

DetecRect::DetecRect(QWidget* parent) : 
QGraphicsView(parent)
{
scene = new QGraphicsScene(this);
pixmapItem=new QGraphicsPixmapItem(pixmap);
scene->addItem(pixmapItem);
this->setScene(scene);
this->setMouseTracking(true);
scene->installEventFilter(this);
}
bool DetecRect::eventFilter(QObject *watched, QEvent *event)
{
if(watched == scene){
// press event
QGraphicsSceneMouseEvent *mouseSceneEvent;
if(event->type() == QEvent::GraphicsSceneMousePress){
mouseSceneEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
if(mouseSceneEvent->button() & Qt::LeftButton){
}
// move event
} else if (event->type() == QEvent::GraphicsSceneMouseMove) {
mouseSceneEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
//selectedItem is a QGraphicsItem
if(this->selectedItem && this->selectedItem->type() == QGraphicsRectItem::Type){
selectedItem->setCursor(Qt::PointingHandCursor);
}
}
// release event
else if (event->type() == QEvent::GraphicsSceneMouseRelease) {
mouseSceneEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
}
}
return QGraphicsView::eventFilter(watched, event);
}

在这段代码中,如果我点击一次,光标就会发生变化。但是,如果我直接传递,请不要更改。为什么?

您不必实现hoverEnterEvent方法或hoverLeaveEvent,只需将光标设置为项目,如下所示:

#include <QApplication>
#include <QGraphicsRectItem>
#include <QGraphicsView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsView view;
QGraphicsScene *scene = new QGraphicsScene(&view);
view.setScene(scene);
QGraphicsRectItem *rit = scene->addRect(QRectF(-50, -50, 100, 100), QPen(Qt::black), QBrush(Qt::gray));
rit->setCursor(Qt::CrossCursor);
QGraphicsRectItem *rit2 = new QGraphicsRectItem(QRectF(-50, -50, 100, 100));
rit2->setPen(QPen(Qt::white));
rit2->setBrush(QBrush(Qt::green));
rit2->setCursor(Qt::PointingHandCursor);
rit2->setPos(200, 100);
scene->addItem(rit2);
view.resize(640, 480);
view.show();
return a.exec();
}