PyQt:悬停按钮时更改光标

2024-03-12

我正在尝试制作一个按钮(或任何其他 Qwidget),这将在悬停时更改用户光标。

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

我正在使用 Qt 样式表,所以我不完全确定,但是有没有办法在那里做类似的事情?,应该看起来像这样:

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

注意:上面的代码是示例,第二行根本没有任何功能。


但是,如果没有,是否还有其他方法可以实现这一目标?


对于任何想在 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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PyQt:悬停按钮时更改光标 的相关文章

随机推荐