Jonas
Jonas

Reputation: 1847

How set options for a QInputDialog

I am trying to set some options for my QInputDialog. But if I call getText these settings have no effect.

How do I change the appearance of the window that pops up from getText?

import sys
from PyQt5 import QtWidgets, QtCore


class Mywidget(QtWidgets.QWidget):
    def __init__(self):
        super(Mywidget, self).__init__()
        self.setFixedSize(800, 600)

    def mousePressEvent(self, event):
        self.opendialog()

    def opendialog(self):
        inp = QtWidgets.QInputDialog()

        ##### SOME SETTINGS
        inp.setInputMode(QtWidgets.QInputDialog.TextInput)
        inp.setFixedSize(400, 200)
        inp.setOption(QtWidgets.QInputDialog.UsePlainTextEditForTextInput)
        p = inp.palette()
        p.setColor(inp.backgroundRole(), QtCore.Qt.red)
        inp.setPalette(p)
        #####

        text, ok = inp.getText(w, 'title', 'description')
        if ok:
            print(text)
        else:
            print('cancel')

if __name__ == '__main__':
    qApp = QtWidgets.QApplication(sys.argv)
    w = Mywidget()
    w.show()
    sys.exit(qApp.exec_())

Upvotes: 1

Views: 5514

Answers (1)

ekhumoro
ekhumoro

Reputation: 120578

The get* methods are all static, which means they can be called without having an instance of the QInputDialog class. Qt creates an internal dialog instance for these methods, so your settings will be ignored.

To get your example to work, you need to set a few more options and then show the dialog explicitly:

def opendialog(self):
    inp = QtWidgets.QInputDialog(self)

    ##### SOME SETTINGS
    inp.setInputMode(QtWidgets.QInputDialog.TextInput)
    inp.setFixedSize(400, 200)
    inp.setOption(QtWidgets.QInputDialog.UsePlainTextEditForTextInput)
    p = inp.palette()
    p.setColor(inp.backgroundRole(), QtCore.Qt.red)
    inp.setPalette(p)

    inp.setWindowTitle('title')
    inp.setLabelText('description')
    #####

    if inp.exec_() == QtWidgets.QDialog.Accepted:
        print(inp.textValue())
    else:
        print('cancel')

    inp.deleteLater()

So now you are more or less reimplementing everything that getText does.

Upvotes: 3

Related Questions