QtWidgets 中来自 QInputDialog 的两个输入

Two inputs from QInputDialog in QtWidgets

text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')

使用我分享的这段代码,我只能从用户那里获得一个输入。有什么方法可以从 QtWidgets 中的 QInputDialog 获取两个输入?我不想为这种情况创建一个新的 window。如果可能的话,我想要的只是从 QInputDialog 获得两个输入。

您必须将 QLineEdit 注入 QInputDialog:

import sys
from PyQt5 import QtWidgets


def get_text_values(initial_texts, parent=None, title="", label=""):
    dialog = QtWidgets.QInputDialog()
    dialog.setWindowTitle(title)
    dialog.setLabelText(label)
    dialog.show()
    # hide default QLineEdit
    dialog.findChild(QtWidgets.QLineEdit).hide()

    editors = []
    for i, text in enumerate(initial_texts, start=1):
        editor = QtWidgets.QLineEdit(text=text)
        dialog.layout().insertWidget(i, editor)
        editors.append(editor)

    ret = dialog.exec_() == QtWidgets.QDialog.Accepted
    return ret, [editor.text() for editor in editors]


def main():
    app = QtWidgets.QApplication(sys.argv)
    ok, texts = get_text_values(
        ["hello", "world"], title="Input Dialog", label="Enter your name:"
    )
    print(ok, texts)


if __name__ == "__main__":
    main()

你的情况:

ok, texts = get_text_values(
    ["hello", "world"], title="Input Dialog", label="Enter your name:", parent=self
)
print(ok, texts)