python - 从主 PyQt 窗口启动 PyQT 窗口,并获取用户输入?

标签 python pyqt

我有一个 PyQt 主窗口,当用户按下某个按钮时,我需要从中获取一串用户输入。

这是我的用户输入窗口代码:

 class InputDialog(QtGui.QDialog):
   '''
   this is for when you need to get some user input text
   '''
   def __init__(self, parent=None, title='user input', label='comment', text=''):

       QtGui.QWidget.__init__(self, parent)

       #--Layout Stuff---------------------------#
       mainLayout = QtGui.QVBoxLayout()

       layout = QtGui.QHBoxLayout()
       self.label = QtGui.QLabel()
       self.label.setText(label)
       layout.addWidget(self.label)

       self.text = QtGui.QLineEdit(text)
       layout.addWidget(self.text)

       mainLayout.addLayout(layout)

       #--The Button------------------------------#
       layout = QtGui.QHBoxLayout()
       button = QtGui.QPushButton("okay") #string or icon
       self.connect(button, QtCore.SIGNAL("clicked()"), self.close)
       layout.addWidget(button)

       mainLayout.addLayout(layout)
       self.setLayout(mainLayout)

       self.resize(400, 60)
       self.setWindowTitle(title)

从主窗口,我说:

inputter = InputDialog(mainWindowUI, title="comments", label="comments", text="")
inputter.show()
comment = inputter.text.text()
print comment

这会打印一个空字符串,即使用户键入评论并点击“确定”也是如此。显然是因为主窗口脚本不等待 InputDialog 关闭。那么,如何让它等待,以便我可以检索用户输入?

最佳答案

使用

inputter.exec_()

代替

inputter.show()

发件人:http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdialog.html#exec

This method is also a Qt slot with the C++ signature int exec().

Shows the dialog as a modal dialog, blocking until the user closes it. The function returns a DialogCode result.

If the dialog is application modal, users cannot interact with any other window in the same application until they close the dialog. If the dialog is window modal, only interaction with the parent window is blocked while the dialog is open. By default, the dialog is application modal.

See also open(), show(), result(), and setWindowModality().

关于python - 从主 PyQt 窗口启动 PyQT 窗口,并获取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7046882/

相关文章:

python - 使用 SQLAlchemy (Python) 创建模型对象时生成 GUID

Python Pandas : Best strategy to import heterogenious csv file

python - 如何平移/拖动/移动QGraphicsScene?

python - 信号发射仅在一种功能中起作用,但在其他功能中不起作用?

python - 有人可以给我推荐一本好的 PyQt/PySide 教程/书籍/视频系列吗?

python - 如何取 numpy 数组的 n 阶离散和(相当于 numpy.diff 的和)

python - 使用 beautifulsoup 从 HTML 中去除值

python - 当传递参数或条件匹配时如何用装饰器装饰函数

python - 如何在Nuke中通过Python创建无框架的自定义面板?

python - 恢复文件的 HTTP 下载和 HTTP 压缩