PyQt:当鼠标悬停在按钮上时更改光标

11

我想制作一个按钮(或其他Qwidget),当用户将鼠标悬停在上面时,可以改变其光标。

例如,当我将鼠标悬停在QPushButton上时,它会将光标从箭头更改为指向手。

我正在使用Qt Style Sheet,所以我不确定是否可以在那里做这样的事情,应该看起来像这样:

btn.setStyleSheet("#btn {background-image: url(':/images/Button1.png'); border: none; }"
"#btn:hover { change-cursor: cursor('PointingHand'); } 

注意:以上代码仅为示例,第二行没有任何功能。


但是,如果不行的话,是否还有其他方法可以实现这个目标?

3个回答

19

如果有人想要在PyQt5中实现这个功能,这是我是如何做到的。假设你有一个按钮,并且当你将鼠标悬停在按钮上时,你希望光标变为“PointingHandCursor”。

你可以使用your_button.setCursor(QCursor(QtCore.Qt.PointingHandCursor))来实现。例如:

from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel, QProgressBar, 
    QLineEdit, QFileDialog
from PyQt5 import QtGui, QtCore
from PyQt5.QtGui import QCursor

import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.title = "your_title"

        self.screen_dim = (1600, 900)

        self.width = 650
        self.height = 400

        self.left = int(self.screen_dim[0]/2 - self.width/2)
        self.top = int(self.screen_dim[1]/2 - self.height/2)

        self.init_window()

    def init_window(self):
        self.setWindowIcon(QtGui.QIcon('path_to_icon.png'))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setStyleSheet('background-color: rgb(52, 50, 51);')

        self.create_layout()

        self.show()

    def create_layout(self):
        self.button = QPushButton('Click Me', self)
        self.button.setCursor(QCursor(QtCore.Qt.PointingHandCursor))

if __name__ == '__main__':

    App = QApplication(sys.argv)
    window = Window()
    sys.exit(App.exec())

3
非常好,您编写了一个独立的代码片段来展示功能! - K.Mulier
很好...完美运行。 - Jenova
请展示所有必要的导入,并感谢您的配合。 - analytical_prat

5

我该如何将它设置为指向手光标?我在文档中找不到它的任何信息。 - ShellRox
1
嘿,来看看文档吧...在第二个链接中,点击“预定义光标对象列表”... - galinette
2
btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)),我尝试了这个方法,它可以正常打开,但光标只会显示一次,我需要循环执行还是其他操作吗? - ShellRox

0

对于Pyqt6,您可以使用以下代码:

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QCursor
closeBtn = QPushButton("X")

closeBtn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接