python - 使用setStyleSheet时在PyQt5中更改QMessageBox的按钮字体?
问题描述
考虑这个例子,大部分来自https://pythonbasics.org/pyqt-qmessagebox/:
import sys
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
defaultfont = QtGui.QFont('Arial', 8)
def window():
app = QApplication(sys.argv)
win = QWidget()
button1 = QPushButton(win)
button1.setText("Show dialog!")
button1.move(50,50)
button1.clicked.connect(showDialog)
win.setWindowTitle("Click button")
win.show()
sys.exit(app.exec_())
def showDialog():
msgBox = QMessageBox()
msgBox.setStyleSheet("QLabel{min-width: 200px;}")
msgBox.setFont(defaultfont)
#msgBox.button(QMessageBox.Ok).setFont(defaultfont) # nowork, msgBox.button(QMessageBox.Ok) is None
#print(msgBox.buttons()) # []
#print(msgBox.findChildren(QtWidgets.QDialogButtonBox)) # [<PyQt5.QtWidgets.QDialogButtonBox object at 0x0000000005f950d0>]
#print(msgBox.findChildren(QtWidgets.QDialogButtonBox)[0].buttons()) # []
#print(msgBox.findChildren(QtWidgets.QDialogButtonBox)[0].standardButtons()) # <PyQt5.QtWidgets.QDialogButtonBox.StandardButtons object at 0x0000000005f60580>
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("Message box pop up window")
msgBox.setWindowTitle("QMessageBox Example")
msgBox.buttonClicked.connect(msgButtonClick)
returnValue = msgBox.exec_()
if returnValue == QMessageBox.Ok:
print('OK clicked')
def msgButtonClick(i):
print("Button clicked is:",i.text())
if __name__ == '__main__':
window()
如代码所示,我尝试应用msgBox.setFont(defaultfont)
-确实,它确实更改了大多数消息的字体-但如果存在该行,它不会更改按钮的字体msgBox.setStyleSheet("QLabel{min-width: 200px;}")
;在这种情况下,这就是 Raspberry Pi 上的样子:
但是,如果您注释 line msgBox.setStyleSheet("QLabel{min-width: 200px;}")
,则字体也会应用于按钮:
那么,我怎样才能既使用setStyleSheet
命令,又更改消息框的字体 - 用于文本和按钮?(我知道窗口标题栏字体受操作系统控制,不能通过 pyqt5 更改)。
解决方案
添加到您的代码中,这一行:
msgBox.setStyleSheet("QPushButton {color:red; font-family: Arial; font-size:8px;}")
msgBox 上的按钮 Ok 将变为红色,并且您的字体!经测试!