我的GUI主要是包装各种后台PowerShell脚本,执行一些自动化功能。有点离题万里,但好吧,这就是我被卡住的地方。
我在Qt Designer中设计了我的界面,输出到一个.ui文件,通过PySide2-UIC转换为.py文件,还有一个mainwindow类,它是我在Qt Designer中创建的主窗口类的一个子类。一切都很顺利。没有任何问题。
我现在正在进行我的编程中的一个部分,我正在从QWidgets(正在工作)捕捉表单数据到一个列表中。我有一个完全自定义编写的类,旨在处理用户输入,设置其他变量,如文件名或某些需要的配置文件的路径,并执行一个包含所有信息的子进程PowerShell命令。我的困惑在于,我试图确定在什么地方实例化这个自定义对象是正确的,在我的MainWindow类里面,还是在我的MainWindow类外面?但如果是这样,在哪里呢?这里有一些简化的代码来帮助解释我的困境。
接口序列
疑问:
更新 我能够清除PyCharm中 "import self "的错误。它与不正确的空格与制表符有关,尽管我只用制表符键来做缩进。我可能需要去仔细检查一下我的inpection设置。其他问题仍然存在。在哪里调用我的自定义类的方法来 "形成一个命令 "和 "运行一个命令 "是最好的,应该由mainWindow类来执行,还是我应该在customObject类上设置一个标志,然后触发那些其他的操作?或者更一般地说,一个对象应该负责执行它自己的functionmethods,有些东西告诉我通常不是,但我不能确定。另外,如果有这方面的书籍,我很乐意自己去研究。我目前正在看《快速GUI编程》,但还不知道后面的章节中是否涉及到这个话题。
如果这个问题不清楚,我很抱歉。我保证会在必要时更新,以帮助解决这个问题。
下面是来简化的代码示例。
class customClass(object): # this is actually in a separate file but for argv sake
def __init__(self):
self.userInput = ""
self.file1 = ""
self.file2 = ""
self.otherstuff...
def setUserInput(self, uinput):
self.userInput = uinput
def dostuffwithdata(self):
# method to execute subprocess command
class MainWindow( QMainWindow ):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.customObject = customClass.customCmdClass()
self.cmddata = dict()
self.ui.toolButton.clicked.connect(self.getformdata)
def getformdata(self):
# recurses through QWidgets and grabs QLabels and QLineEdit.Text() and updates dict()
for w in widgets:
if w is qlabel:
k = w.text()
v = w.buddy().text()
self.cmddata.update({k: v})
""" all the above works fine. what doesn't work is this part"""
# at this point I want to send the collected data to the customObject for processing
def senddatatocustomObject(self):
self.customObject.setUserInput(self.cmddata) """but this says that 'self' isn't defined.
I know it has to be because of the object in an object, or something I'm doing wrong here.
**Update**: figured this out. PyCharm was freaking out about some sort of
perceived indentation error despite there not appearing to actually be one.
Was able to correct this. """
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
为了结束这个问题,我对我之前发布的关于 "逻辑 "和流程放在哪里的问题给出了这个答案。
考虑到这是一个没有任何后端服务的图形化应用程序,将大部分的用户交互逻辑和流程放在MainWindow对象中是最有意义的,因为它基本上是我程序的控制中心。当用户点击或输入某些内容时,它将发生在MainWindow上,当状态发生变化时,它将发生在MainWindow上(大部分)或以某种方式直接与MainWindow联系在一起。因此,将我的大部分方法调用、用户输入流逻辑和其他代码,包含在我的程序的MainWindow类对象中是有意义的。
我的其他类和对象是为了捕获状态和对不同的数据集执行操作,但在大多数情况下,这些辅助类对象应该由我的应用程序的MainWindow控制。
这当然不是编写这个应用程序或其他应用程序的唯一方法,但我相信这至少回答了我之前发布的问题。