PyQt:悬停按钮时更改光标 [英] PyQt: Changing cursor when hovering a button

查看:37
本文介绍了PyQt:悬停按钮时更改光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个按钮(或任何其他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

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())

这篇关于PyQt:悬停按钮时更改光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆