簡體   English   中英

從主 PyQt window 啟動 PyQT window,並獲取用戶輸入?

[英]launch a PyQT window from a main PyQt window, and get the user input?

我有一個主要的 PyQt window,當他們點擊某個按鈕時,我需要從中獲取一串用戶輸入。

這是我的用戶輸入 window 的代碼:

 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)

從主要的 window,我說:

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

即使用戶鍵入評論並點擊“確定”,這也會打印一個空字符串。 顯然是因為主 window 腳本不會等待InputDialog關閉。 那么,我如何讓它等待,以便我可以檢索用戶輸入?

利用

inputter.exec_()

代替

inputter.show()

來自: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdialog.html#exec

此方法也是一個 Qt 插槽,帶有 C++ 簽名 int exec()。

將對話框顯示為模態對話框,在用戶關閉它之前一直處於阻塞狀態。 function 返回 DialogCode 結果。

如果對話框是應用程序模式,則用戶在關閉對話框之前無法與同一應用程序中的任何其他 window 交互。 如果對話框是 window 模態的,則在對話框打開時僅阻止與父 window 的交互。 默認情況下,對話框是應用程序模式。

另請參見 open()、show()、result() 和 setWindowModality()。

我知道 utdemir 的回復解決了您的問題,但我只想說 Qt 附帶了幾個方便的輸入對話框。 例如,看看QInputDialog.getText

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM