首页 > 解决方案 > 如何将 InputDialog 的输入打印到对话框本身?

问题描述

我有这个应用程序:

在此处输入图像描述

我要这个:

在此处输入图像描述

我的问题:

  1. 我不确定如何实现
  2. 完成输入对话框后会弹出主窗口

到目前为止我所拥有的:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'My First PyQt5 Window'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.getText()

        self.show()

    def getText(self):
        text, ok = QInputDialog.getText(self, "Get text", "Your name:", QLineEdit.Normal, "")
        if ok and text != '':
            print(text)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

标签: pythonpyqtpyqt5

解决方案


您必须修改 QInputDialog 但如果您使用静态方法 getText() 它很复杂,相反您必须创建 QInputDIalog 作为实例,然后添加具有必要连接的 QLabel:

def getText(self):

    dialog = QInputDialog(self)
    dialog.setWindowTitle("Get text")
    dialog.setLabelText("Your name:")
    dialog.setTextValue("")
    dialog.setTextEchoMode(QLineEdit.Normal)
    dialog.show()
    label = QLabel()

    def on_text_changed(text):
        label.setText("you printed {}".format(text))

    le = dialog.findChild(QLineEdit)
    le.textEdited.connect(on_text_changed)
    on_text_changed(le.text())
    dialog.layout().insertWidget(2, label, alignment=Qt.AlignCenter)
    ret = dialog.exec_()
    ok = bool(ret)
    text = dialog.textValue() if ret else ""
    if ok:
        print(text)

推荐阅读