从变量中获取文本并将其显示在不同类的QLineedit中

时间:2016-03-14 15:25:50

标签: python pyqt qlineedit

我正在尝试从A类中获取可验证的文本,并在QLineEdit中使用它的文本,以便每次文本在变量中发生变化时显示它。 像这样:

class A(self):
  variable = None

  def __init__(self):
    pass

  def get_text(self):
    self.variable = "Hello" #Every time that this value changes, it must be shown in the QLineEdit

class B(self):
  def __init__(self):
    pass

  def show_text(self):
    qle = QLineEdit()
    qle.setText(A.variable)

我要做的是获取鼠标的坐标,将其设置为str,并在我QLineEditQDialog中显示QtDesigner }

我怎样才能做到这一点?希望你能帮帮我。

修改

我需要class B成为QDialog。我添加了一些更改,使其更具可读性。

class A(QMainWindow):
  def __init__(self):
    pass

  def get_text(self, event):
    if event.button == 1:
      self.variable = event.xdata

  @property
  def variable(self):
    self.b.qle.setText()

  @variable.setter
  def variable(self, value):
    self.b.qle.setText(value) 

class B(QDialog):
  def __init__(self, parent):
    QDialog.__init__(self, None)
    # you need to store the lineedit as a instance attribute of B so it can be accessed in A
    self.qle = QLineEdit()

我有什么遗失的吗?

1 个答案:

答案 0 :(得分:1)

您可以将变量定义为Python属性,以便每次更新变量时都可以运行方法。如果您想在存储之前对值进行检查(例如,确保它是有效数字或您想要的任何内容),这也很有用。

你可以这样做:

class A(self):
  variable = None

  def __init__(self):
    # you need a reference to the instance of the B class for this to work. 
    # dependning on how you create B currently, you might need to adapt this code
    self.b = B() 

  def get_text(self):
    self.variable = "Hello" #Every time that this value changes, it must be shown in the QLineEdit

  @property
  def variable(self):
    return self.b.qle.text()

  @variable.setter
  def variable(self, value):
    # do any checks you want
    self.b.qle.setText(value)

class B(self):
  def __init__(self):
    # you need to store the lineedit as a instance attribute of B so it can be accessed in A
    self.qle = QLineEdit()

如果您不想在B内实例化A,则可以在实例化A时传入对行编辑的引用。