[英]How to modify the font in a layout in the About section in PyQt5?
about
function 是一个static方法:它是一个“助手”,它自动构造一个消息框,运行它的exec()
并返回它的结果。 这意味着无法访问消息框实例,因此无法访问其字体。
请注意,由于它是 static 方法,因此创建 QMessageBox 的新实例没有用,因为您可以单独调用about
:
QMessageBox.about(self.parent(), "About", "Appli\nVersion 0.0")
根据消息来源,在 MacOS 上,Qt 自动为所有消息框的 label 使用粗体。
解决方法是避免使用 static 方法,并创建一个新的 QMessageBox 实例。 Since the label widget is private, the only way to access it is through findChild()
, which on PyQt allows us to use both a class and an object name; 幸运的是,Qt 为 label ( qt_msgbox_label
) 设置了 object 名称,因此我们可以访问它并相应地设置字体:
def showAbout(self):
msgBox = QMessageBox(QMessageBox.NoIcon, 'About', 'Appli\nVersion 0.0',
buttons=QMessageBox.Ok, parent=self.parent())
# find the QLabel
label = msgBox.findChild(QLabel, 'qt_msgbox_label')
# get its font and "unbold" it
font = label.font()
font.setBold(False)
# set the font back to the label
label.setFont(font)
msgBox.exec_()
试试看:
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowIcon(QtGui.QIcon("icono.png"))
menu = self.menuBar().addMenu("Menu")
self.actionAbout = menu.addAction("About")
self.actionAbout.triggered.connect(self.openAbout)
@QtCore.pyqtSlot()
def openAbout(self):
messagebox = QtWidgets.QMessageBox(
QtWidgets.QMessageBox.NoIcon,
"About",
"""
<p style='color: white; text-align: center;'> Appli<br>
<b style='color: yellow; font: italic bold 16px;'>Version 0.0</b>
</p>
""",
parent=self,
)
messagebox.setIconPixmap(QtGui.QPixmap("Qt.png").scaled(100, 100, QtCore.Qt.KeepAspectRatio))
messagebox.setAttribute(QtCore.Qt.WA_DeleteOnClose)
messagebox.setStyleSheet("""
QMessageBox {
border: 5px solid blue;
border-radius: 5px;
background-color: rgb(100, 1, 1);
}
""")
messagebox.exec_()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.