Search code examples
pythonpyside

How to set up QMessageBox text format?


I want to set up QMessageBox text format, but I can't find a valid method.

QtGui.QMessageBox.information(
    self, 
    "Confirm delete!", 
    "Are you sure you want to delete file?\n %s" % filename,
    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
    QtGui.QMessageBox.No
)

I want to make bold, like:

"Are you sure you want to delete file?\n <b>%s</b>"

How can I do this?


Solution

  • According to PySide's documentation you can use the setTextFormat to specify the Qt.RichText format.

    However this will only work when you create a custom QMessageBox instance and then set it up, it will not work when using the QMessageBox.information static-method.

    By default QMessageBox uses the Qt.AutoText format which tries to detect whether the text is rich text by using the Qt.mightBeRichText function (I could only find Qt's documentation). The documentation of that function states:

    Returns true if the string text is likely to be rich text; otherwise returns false.

    This function uses a fast and therefore simple heuristic. It mainly checks whether there is something that looks like a tag before the first line break. Although the result may be correct for common cases, there is no guarantee.

    Unfortunately in your message you have a line break \n before any tag, and hence the function fails to detect your message as rich text.

    In any case once you interpret the text as rich text you have to use the HTML line break <br> so using the message:

    "Are you sure you want to delete file?<br> <b>%s</b>"
    

    will make the QMessageBox auto-detect the rich text and produce the result you want.