【问题标题】:PyQt5: How to set a custom mouse pointer for each role?PyQt5:如何为每个角色设置自定义鼠标指针?
【发布时间】:2019-10-02 08:13:45
【问题描述】:

1。简介

我正在 Python 3.7 中使用 PyQt5 为 GUI 创建一个应用程序。我想在应用程序中自定义鼠标光标。

让我们从 Qt5 中设置的标准光标开始,如下表所示: https://doc.qt.io/qt-5/qt.html#CursorShape-enum。您会注意到 Qt5 有一个专用的 Enum Qt::CursorShape 描述相应游标的作用。例如:

 
我想用 custom 替换每个 Standard Qt cursor

 

2。第一种方法

起初我尝试过这样的事情:

pixmap = QPixmap("C:/../my_arrow.png")
cursor = QCursor(pixmap, 32, 32)
QApplication.setOverrideCursor(cursor)

不幸的是,这种方法不适合我的目的。来自文档:

应用程序覆盖光标旨在向用户显示应用程序处于特殊状态,例如在可能需要一些时间的操作期间。

在调用restoreOverrideCursor() 或另一个setOverrideCursor() 之前,覆盖光标将显示在所有应用程序的小部件中。

换句话说,使用setOverrideCursor() 方法有两个缺点:

  1. 我必须手动跟踪鼠标指针应更改为哪个角色,每次调用 setOverrideCursor() 并输入正确的 QCursor()

  2. 我需要跟踪 Qt 自动调用 restoreOverrideCursor() 的位置,因为这会有效地撤消我自己的更改。这将是一场与 Qt 的持续战斗。

 

3。第二种方法

我的第二种方法是使用 setCursor() 函数:

pixmap = QPixmap("C:/../Arrow.png")
cursor = QCursor(pixmap, 32, 32)
my_widget.setCursor(cursor)

我在顶级小部件 - QMainWindow() 上执行此操作 - 以便将效果应用于整个应用程序。

效果很好,但也有一个缺点。此功能仅更改“默认光标”(指向箭头),仅此而已。所有的特殊光标还是一样的。

 
事实上,我想做这样的事情:

# Note: 'mainwin' is the QMainWindow().
mainwin.setCursor( QCursor(QPixmap("C:/../Arrow.png"),     32, 32), Qt.ArrowCursor     )
mainwin.setCursor( QCursor(QPixmap("C:/../UpArrow.png"),   32, 32), Qt.UpArrowCursor   )
mainwin.setCursor( QCursor(QPixmap("C:/../Cross.png"),     32, 32), Qt.CrossCursor     )
mainwin.setCursor( QCursor(QPixmap("C:/../Wait.png"),      32, 32), Qt.WaitCursor      )
mainwin.setCursor( QCursor(QPixmap("C:/../IBeam.png"),     32, 32), Qt.IBeamCursor     )
mainwin.setCursor( QCursor(QPixmap("C:/../SizeVer.png"),   32, 32), Qt.SizeVerCursor   )
mainwin.setCursor( QCursor(QPixmap("C:/../SizeHor.png"),   32, 32), Qt.SizeHorCursor   )
mainwin.setCursor( QCursor(QPixmap("C:/../SizeBDiag.png"), 32, 32), Qt.SizeBDiagCursor )
mainwin.setCursor( QCursor(QPixmap("C:/../SizeFDiag.png"), 32, 32), Qt.SizeFDiagCursor )
...

很遗憾,setCursor() 函数不是这样工作的。

 
您有最符合我目的的解决方案吗?

 

4。资源

我从以下来源学到了很多东西:

不幸的是,他们都没有为我的问题提供解决方案。我只是在这里提到它们,因为它们与我正在尝试做的事情相关 - 但与(!)不同。

【问题讨论】:

  • 恕我直言,无法更改游标,因为它的实现是在 Qt 的私有 api 中
  • 嗨@eyllanesc,感谢您查看问题。让我们希望有办法做到这一点。老实说,我不知道怎么做 - 但这就是 StackOverflow 的用途:-)
  • This 还谈到了你想做的事情。他们的结果也是不可能的。我认为一般的问题是操作系统绘制了光标(我对此是否正确?)并且当光标改变时你无法得到通知或其他东西。

标签: python qt pyqt qt5 pyqt5


【解决方案1】:
# I'm coming```.

# 1. Set the cursor map
self.cursor_pix = QPixmap('exa.png')

# 2. Scale textures
self.cursor_scaled_pix = self.cursor_pix.scaled(QSize(20, 20), Qt.KeepAspectRatio)

# 3. Set cursor style and cursor focus position
self.current_cursor = QCursor(self.cursor_scaled_pix, -1, -1)

# 4. Set the cursor for the specified window
widget.setCursor(self.current_cursor)

【讨论】:

  • 请考虑解释您的代码。没有任何cmets,代码对其他人的价值就很小
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2016-06-15
相关资源
最近更新 更多