如何设置QInputDialog的选项

时间:2017-10-19 08:45:52

标签: python pyqt pyqt5 qinputdialog

我正在尝试为QInputDialog设置一些选项。但如果我拨打getText这些设置无效。

如何更改从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_())

1 个答案:

答案 0 :(得分:1)

get*方法都是 static ,这意味着可以在没有QInputDialog类实例的情况下调用它们。 Qt为这些方法创建了一个内部对话框实例,因此您的设置将被忽略。

要让您的示例正常工作,您需要设置更多选项,然后明确显示对话框:

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()

所以现在你或多或少地重新实现了getText所做的一切。