如何在PyQt5中使用connect从另一个类调用方法

时间:2018-06-14 13:26:41

标签: python python-3.x pyqt pyqt5

我正在尝试使用以下结构创建一个简单的GUI应用程序

class MainWindow(QMainWindow):

def __init__(self):
    super().__init__()
    self.init_ui()

def init_ui(self):
    self.table_widget = MainTabWindow()
    self.setCentralWidget(self.table_widget)
    self.show()



class MainTabWindow(QTabWidget):

def __init__(self,parent=None):
    #super(QWidget, self).__init__(parent)
    super(MainTabWindow, self).__init__(parent)
    self.init_ui()

def init_ui(self):
    self.setWindowTitle('PyQt5 Tab Example')

    self.layout = QVBoxLayout(self)
    #self.selected_date = QDate.currentDate()
    #self.tabs = QTabWidget()
    self.tab1 = QWidget()
    self.tab2 = QWidget()
    self.tab3 = QWidget()
    self.tab4 = QWidget()
    #self.buttonLayout = QMainWindow()

    self.addTab(self.tab1,"Search")
    self.addTab(self.tab2,"Add/Update")
    self.addTab(self.tab3,"Billing Summary")
    self.addTab(self.tab4,"Search2")

    self.SearchTab()
    self.PGCreationTab()
    self.BillingSummaryTab()

def PGCreationTab(self):
  layout = QFormLayout()
  policy = QSizePolicy()
  layout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2))
  PG_obj = PGDetails()
  fn = PG_obj.setFirstName()
  layout.addRow("FirstName",fn)
  fn.textChanged.connect(PG_obj.getText)

def main():
    application = QApplication(sys.argv)
    main_window = MainTabWindow()
    main_window.show()
    sys.exit(application.exec_())

if __name__ == '__main__':
    main()

PGDetails类 -

class PGDetails():

def __init__(self,parent=None):
    self.obj = 5
    #self.FirstName = QLineEdit()
    #self.FirstName.setValidator(QIntValidator())

def setFirstName(self):
    self.FirstName = QLineEdit()
    #print("Inside")
    #print(self.FirstName.text())
    return self.FirstName

def getText(self):
    print("Inside")
    print(self.FirstName.text())

我无法在First name行框中检查是否有任何文本更改,函数getText永远不会被调用。

如果我使用self,它会抛出错误,因为未在MainTabWindow中定义getText

如何从MainTabWindow类中调用函数getText

1 个答案:

答案 0 :(得分:0)

从函数创建的变量仅存在,直到函数结束,除非其范围更大,在您的情况下PG_obj是一个局部变量,将在PGCreationTab函数结束时删除。解决方案是让PG_obj具有更大的范围,例如使其成为MainTabWindow类的成员。

...
self.PG_obj = PGDetails()
fn = self.PG_obj.setFirstName()
layout.addRow("FirstName",fn)
fn.textChanged.connect(self.PG_obj.getText)