Skip to main content
 首页 » 编程设计

python之如何在 PyQt 中更改 QInputDialog 的字体大小

2024年10月17日8shihaiming

简单消息框的案例

我已经弄清楚如何在简单的 PyQt 对话框窗口中更改字体大小。举个例子:

    # Create a custom font 
    # --------------------- 
    font = QFont() 
    font.setFamily("Arial") 
    font.setPointSize(10) 
 
    # Show simple message box 
    # ------------------------ 
    msg = QMessageBox() 
    msg.setIcon(QMessageBox.Question) 
    msg.setText("Are you sure you want to delete this file?") 
    msg.setWindowTitle("Sure?") 
    msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) 
    msg.setFont(font) 
    retval = msg.exec_() 
    if retval == QMessageBox.Ok: 
        print('OK') 
    elif retval == QMessageBox.Cancel: 
        print('CANCEL') 

更改字体大小的关键是您实际上有一个消息框的“句柄”。变量 msg 可用于在使用 msg.exec_() 显示之前根据您的需要调整消息框。

简单输入对话框的案例

关于输入对话框的问题是没有这样的句柄。举个例子:

    # Show simple input dialog 
    # ------------------------- 
    filename, ok = QInputDialog.getText(None, 'Input Dialog', 'Enter the file name:') 
    if(ok): 
        print('Name of file = ' + filename) 
    else: 
        print('Cancelled') 

输入对话框对象是即时创建的。我无法根据需要调整它(例如,应用不同的字体)。

有没有办法在显示之前获取此 QInputDialog 对象的句柄?

编辑:

我在评论中被建议使用 HTML 片段来尝试:

    filename, ok = QInputDialog.getText(None, 'Input Dialog', '<html style="font-size:12pt;">Enter the file name:</html>') 

结果如下:

如您所见,文本输入字段仍具有较小(未更改)的字体大小。

请您参考如下方法:

感谢@denvaar 和@ekhumoro 的评论,我得到了解决方案。在这里:

    # Create a custom font 
    # --------------------- 
    font = QFont() 
    font.setFamily("Arial") 
    font.setPointSize(10) 
 
    # Create and show the input dialog 
    # --------------------------------- 
    inputDialog = QInputDialog(None) 
    inputDialog.setInputMode(QInputDialog.TextInput) 
    inputDialog.setWindowTitle('Input') 
    inputDialog.setLabelText('Enter the name for this new file:') 
    inputDialog.setFont(font) 
    ok = inputDialog.exec_() 
    filename = inputDialog.textValue() 
    if(ok): 
        print('Name of file = ' + filename) 
    else: 
        print('Cancelled')