Master Mouse Cursor Customization in PyQt5: From Default to Custom Shapes
This tutorial explains how to change mouse cursor shapes in PyQt5, covering built‑in Qt cursor constants, practical code examples for setting default and hand cursors, and step‑by‑step guidance for creating fully custom cursors using QPixmap and QCursor.
Mouse Shape Settings Code Practice
Set mouse shapes using the
setCursor()method with different Qt cursor constants.
<code># import packages
from PyQt5.Qt import *
import sys
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("鼠标相关操作")
window.resize(500, 500)
# default cursor (arrow)
window.setCursor(Qt.ArrowCursor)
window.show()
sys.exit(app.exec_())
</code>The default arrow cursor appears when the mouse is over the widget; moving the cursor changes its appearance according to the set shape.
Other Cursor Shapes
Example of setting the open‑hand cursor.
<code>window.setCursor(Qt.OpenHandCursor)</code>Custom Mouse Shape
Creating a custom cursor involves three steps: create a QPixmap object, scale it, and use it to construct a QCursor which is then applied with
setCursor(). The custom cursor can be based on any image.
<code># import packages
from PyQt5.Qt import *
import sys
app = QApplication(sys.argv)
window = QWidget()
window.resize(500, 500)
window.setWindowTitle("自定义鼠标样式")
# load image and scale
pixmap = QPixmap("xxx.png")
new_pixmap = pixmap.scaled(50, 50, Qt.KeepAspectRatio)
# create QCursor with hotspot at (0,0)
cursor = QCursor(new_pixmap, 0, 0)
window.setCursor(cursor)
# add a button for interaction
button = QPushButton(window)
button.setText("按钮")
button.move(100, 100)
window.show()
sys.exit(app.exec_())
</code>Running the program shows the window with the custom cursor and a clickable button at the top‑left corner.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.