为QWidget设置一致的鼠标光标



我已经子类化了QWidget,用鼠标在上面绘图。我使用setCursor将其光标更改为十字形状。它工作得很好,但是只要我按下鼠标按钮(例如绘制徒手线),光标就会变回应用程序光标。请注意,我不想在mouseenter事件上使用setOverrideCursor,例如,因为我只想为这个小部件而不是整个应用程序更改光标,并且我有一个更好的解决方案(如下所示)。

我目前的解决方案是使用setCursor(光标());在我的重写mousePressEvent(QMouseEvent * event)和mouseDoubleClickEvent(QMouseEvent * event)后者是因为由于某种原因,双击也会将光标更改为应用程序光标!变通的工作:)但我想看看是否有更好的解决方案,要求QT不改变光标在所有。

我应该补充一下,拖放是不激活的。

下面是一些源代码片段:

class MyWidget : public QWidget
{
    void paintEvent( QPaintEvent * /*event*/ );
    void resizeEvent( QResizeEvent * event );
    void mouseDoubleClickEvent ( QMouseEvent * event );
    void mousePressEvent( QMouseEvent* event );
    void mouseReleaseEvent( QMouseEvent* event );
    void mouseMoveEvent( QMouseEvent* event );
    void wheelEvent( QWheelEvent* event );
}

然后我重写以下内容(用于解决方法)

void MyWidget::mouseDoubleClickEvent(QMouseEvent * event)
{
    // ... do some other stuff ...
    // This is a workaround to prevent the cursor from changing
    setCursor(cursor());
    event->accept();
}
void MyWidget::mousePressEvent(QMouseEvent * event)
{
    // ... do some other stuff ...
    // This is a workaround to prevent the cursor from changing
    setCursor(cursor());
    event->accept();
}

要更改光标,假设mywidget是用我的类实例化的,我这样做:mywidget->setCursor(Qt::CrossCursor)同样,当我将鼠标悬停在控件上时,它会按照预期改变光标,但一旦我按下鼠标按钮(因此需要上述解决方案),它就会变回应用程序光标

QApplication.setOverrideCursor(QtGui.QCursor(Qt.CrossCursor))

,当QWidget关闭时,设置回原来的光标

好吧,我仍然没有找到任何答案,所以这里是解决方案:

void MyWidget::mouseDoubleClickEvent(QMouseEvent * event)
{
    // ... do some other stuff ...
    // This is a workaround to prevent the cursor from changing
    setCursor(cursor());
    event->accept();
}
void MyWidget::mousePressEvent(QMouseEvent * event)
{
    // ... do some other stuff ...
    // This is a workaround to prevent the cursor from changing
    setCursor(cursor());
    event->accept();
}

最新更新