python - 更改 QMessageBox 和 SaveFileDialog 的光标
问题描述
在 PyQt5 中,我可以使用以下方法更改对象的光标:
Object.setCursor(QCursor(Qt.PointingHandCursor))
对于我使用此类的其他按钮,但它不会更改QmessageBox
或中的光标Qfiledialog
:
class QPushButton(QPushButton):
def __init__(self, parent=None):
super(QPushButton, self).__init__(parent)
self.setCursor(QCursor(Qt.PointingHandCursor))
如何更改 和 中所有按钮的QMessageBox
光标QFileDialog
?
消息框方法示例
def onNotConnected(self):
err = QMessageBox.question(
self, DONGLE_NOT_CONN, DONGLE_NOT_CONN_MSG, QMessageBox.Ok | QMessageBox.Cancel)
if err == QMessageBox.Ok:
self.updating_thread(self.device_code)
else:
self.restart_program()
解决方案
QMessageBox
并QFileDialog
拥有该setCursor()
方法,因为它们继承自QWidget
. 但是您的问题在于静态方法,因为您无法直接访问该对象。
所以解决方案是利用这些静态方法的一个特殊特性:它们是顶层,所以我们可以使用 过滤它QApplication.topLevelWidgets()
,但另一个问题是它们是阻塞的,所以不会同步执行任何东西,所以诀窍是使用QTimer
。
from PyQt5 import QtCore, QtGui, QtWidgets
def onTimeout():
for w in QtWidgets.QApplication.topLevelWidgets():
if isinstance(w, QtWidgets.QMessageBox):
for button in w.buttons():
button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent=None)
self.show()
QtCore.QTimer.singleShot(0, onTimeout)
res = QtWidgets.QMessageBox.question(self,
"title",
"text",
QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
同样在您的示例中,我们可以使用 QMessageBox 的父级过滤过滤器,并且可能 QFileDialog 是窗口。
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent=None)
self.show()
QtCore.QTimer.singleShot(0, self.onTimeout)
msgBox = QtWidgets.QMessageBox.question(self,
"title",
"text",
QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
QtCore.QTimer.singleShot(0, self.onTimeout)
fileName, _ = QtWidgets.QFileDialog.getSaveFileName(self,
"Save File",
QtCore.QDir.homePath(),
"Images (*.png *.xpm *.jpg)",
"",
QtWidgets.QFileDialog.DontUseNativeDialog)
def onTimeout(self):
for w in QtWidgets.QApplication.topLevelWidgets():
if isinstance(w, QtWidgets.QMessageBox) and w.parent() == self:
for button in w.buttons():
button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
elif isinstance(w, QtWidgets.QFileDialog) and w.parent() == self:
for button in w.findChildren(QtWidgets.QPushButton):
button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
推荐阅读
- r - 替换字符串中的对象并避免引用
- android - 不错的 Kotlin 方式为 Singelton 创建自定义初始化程序?
- flutter - 等到应用程序在 onLaunch 之后启动,并带有 firebase 消息传递和颤动
- java - 多个应用程序共享一个 MySQL 数据库
- android - Android MaterialDatePicker 布局问题
- vue.js - Vuejs-neo4j 连接器:显示查询中的所有节点
- mysql - 从具有多个相似行的表中选择不同的行
- c# - 没有 EF Core 的 Linq 异步接口
- java - 缓冲阅读器仅读取某些行 java FileReader
- c - 使用 C 中的指针进行矩阵加法