0

我正在探索基于另一个文件的简单类方法自动生成表单的方法。这个想法是,随着我的“items.py”包的增长,“gui.py”会自动保留标签,甚至进行一些验证。我实际上得到了一些工作:

函数文件:

def PrintHelloSomeone(str_someone):
  print "Hello %s" % str_someone

def PrintN(int_N):
  print "%i" % int_N

def PrintRange(int_min, int_max):
  print range(int_min, int_max)

图形用户界面文件:

import inspect
from PySide import QtGui

class AutoForm(QtGui.QFormLayout):
  ARG2GUI = {
    'int' : (QtGui.QSpinBox, 'value'),
    'str' : (QtGui.QLineEdit, 'text'),
  }

  def __init__(self, (name, function)):
    super(AutoForm, self).__init__()
    self.function = function

    self.addRow(QtGui.QLabel(name))

    self.call_list = []
    for arg in inspect.getargspec(function).args:
      self.call_list.append(self.arg2widget(arg))

    button = QtGui.QPushButton("Run")
    button.clicked.connect(self.call_function)
    self.addRow(None, button)

  def arg2widget(self, arg):
    tp, name = arg.split('_')
    widget_obj, call = self.ARG2GUI[tp]
    widget = widget_obj()
    widget_call = getattr(widget, call)
    self.addRow(name, widget)
    return widget_call

  def call_function(self):
    args = [call() for call in self.call_list]
    self.function(*args)

if __name__ == '__main__':
  import sys
  import stuff

  app = QtGui.QApplication(sys.argv)

  w = QtGui.QWidget()
  w.show()
  w.setLayout(QtGui.QHBoxLayout())

  for function in inspect.getmembers(stuff, inspect.isfunction):
    w.layout().addLayout(AutoForm(function))

  sys.exit(app.exec_())

该代码实际上似乎有效,但我想知道是否有更好的方法来做我想做的事情。

4

0 回答 0