Search code examples
pythonpython-3.4pyqt5qlineeditqmessagebox

How to add QLineEdit to QMessageBox PyQt5


I want a copyable text on my QMessageBox so I thought I can put a QLineEdit on QMessageBox then set the text of QLineEdit whatever I want, so user can choose the text and copy it.

But I couldn't success. Is there a way to add QLineEdit to QMessageBox or make a copyable text on QMessageBox?


Solution

  • by playing with QMessageBox.informativeText(), QMessageBox.detailedText() and QMessageBox.textInteractionFlags() i found the following:

    QMessageBox.informativeText() and QMessageBox.detailedText() are always selectable, even if QmessageBox.textInteractionFlags() are set to QtCore.Qt.NoTextInteraction. QMessageBox.detailedText() is shown in a textedit. QMessageBox.setTextInteractionFlags() only acts on QmessageBox.text(). The use of these kinds of text is descripted in documentation of QMessageBox. By flags you can set the text editable and/or selectable, see enum TextInteractionFlags.

    Here an working example with selectable text in QmessageBox.detailedText():

    import sys 
    from PyQt5 import QtWidgets, QtCore
    
    class MyWidget(QtWidgets.QWidget): 
        def __init__(self): 
            QtWidgets.QWidget.__init__(self) 
            self.setGeometry(400,50,200,200)
    
            self.pushButton = QtWidgets.QPushButton('show messagebox', self)
            self.pushButton.setGeometry(25, 90, 150, 25)
            self.pushButton.clicked.connect(self.onClick)
    
        def onClick(self):
            msgbox = QtWidgets.QMessageBox()
            msgbox.setText('to select click "show details"')
            msgbox.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) # (QtCore.Qt.TextSelectableByMouse)
            msgbox.setDetailedText('line 1\nline 2\nline 3')
            msgbox.exec()
    
    app = QtWidgets.QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(app.exec_())