我需要通过点击我的应用中的QPushButton
(通过clicked
)来生成自定义弹出式输入窗口。它需要从不同类型的用户获得几个输入,然后将它们返回到主窗口应用程序内的调用函数。我发现内置函数,例如QInputDialog
,可以为单个特定输入执行此操作,但我无法弄清楚如何在需要输入不同类型的弹出窗口的情况下执行此操作一次(最好是在Qt Designer中设计的窗口中)。有谁知道怎么做?
import sys
import os
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import uic
path = os.path.dirname(__file__) #uic paths from itself, not the active dir, so path needed
qtCreatorFile = "NAME.ui" #Ui file name, from QtDesigner
Ui_MainWindow, QtBaseClass = uic.loadUiType(path + qtCreatorFile) #process through pyuic
class MyApp(QMainWindow, Ui_MainWindow): #gui class
def __init__(self):
#Set up the gui via Qt
super(MyApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.add_button.clicked.connect(self.add_row) #add_button is QPushButton
def add_row(self):
data1, data2, data3 = #popup form to get data (types are not the same)
#do stuff with data
pass
#start app
if __name__ == "__main__":
app = QApplication(sys.argv) #instantiate a QtGui (holder for the app)
window = MyApp()
window.show()
sys.exit(app.exec_())
答案 0 :(得分:3)
没有单一的解决方案,但我会给你一个指导,做你想做的事。
如果你想获得一个带有QInputDialog行为的小部件,你必须先选择正确的模板,在这种情况下,一个好的选择是带按钮底部的Dialog或带按钮的对话框,添加你想要的组件,定位等等
然后,当您展示代码时,您创建了一个继承自QDialog的类,然后创建一个获得结果的方法,但这样做不要使用show()
但exec_()
path = os.path.dirname(__file__)
qtCreatorFile = "some_dialog.ui"
Ui_Dialog, _ = uic.loadUiType(os.path.join(path,qtCreatorFile))
class CustomDialog(QDialog, Ui_Dialog):
def __init__(self):
super(CustomDialog, self).__init__()
self.setupUi(self)
# set initials values to widgets
def getResults(self):
if self.exec_() == QDialog.Accepted:
# get all values
val = self.some_widget.some_function()
val2 = self.some_widget2.some_another_function()
return val1, val2, ...
else:
return None
然后在你的函数中使用它:
class MyApp(QMainWindow, Ui_MainWindow): #gui class
def __init__(self):
#Set up the gui via Qt
super(MyApp, self).__init__()
self.setupUi(self)
self.add_button.clicked.connect(self.add_row) #add_button is QPushButton
def add_row(self):
w = CustomDialog()
values = w.getResults()
if values:
data1, data2, data3 = values