3

更新 3:

这是新代码,试图按照你告诉我的去做,但没有结果......我开始认为我在程序的某个地方做了一些非常愚蠢的事情......有什么新想法吗?

程序.py:

# -*- coding: utf-8 -*-
#imports:
import os
import platform
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import newchilddlg
from newchilddlg import *

#version:
__version__ = "1.0.0"


#Lists:
am = []
courtdate = []
board_number = []
namesurname = []
fathersname = []
mothersname = []
birthday = []
placeofbirth = []
nationality = []
address = []
tel = []
job = []
praxis = []
dayofdoing = []
placeofdoing = [] 
children = [am, courtdate, board_number, namesurname, fathersname, mothersname, birthday, placeofbirth, nationality, address, tel, job, praxis, dayofdoing, placeofdoing]


#Main Window Class:
class MainWindow(QMainWindow):


    #__init__ function:
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        #Window size:
        self.resize(800,600)
        self.centralwidget = QtGui.QWidget(self)
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)

        #Table Widget:
        self.tableWidget = QtGui.QTableWidget(self.centralwidget)
        self.vBar = self.tableWidget.verticalScrollBar()
        self._vBar_lastVal = self.vBar.value()
        self.horizontalLayout.addWidget(self.tableWidget)
        self.vBar.valueChanged.connect(self.scrollbarChanged)
        self.tableWidget.setGridStyle(QtCore.Qt.SolidLine)
        self.tableWidget.setRowCount(100)
        self.tableWidget.setColumnCount(15)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(5, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(6, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(7, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(8, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(9, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(10, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(11, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(12, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(13, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(14, item)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(140)
        self.tableWidget.horizontalHeader().setHighlightSections(True)
        self.tableWidget.horizontalHeader().setStretchLastSection(False)
        self.tableWidget.verticalHeader().setDefaultSectionSize(30)
        self.tableWidget.verticalHeader().setStretchLastSection(False)
        self.horizontalLayout.addWidget(self.tableWidget)
        self.setCentralWidget(self.centralwidget)

        #Window Title:
        self.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.tableWidget.setSortingEnabled(False)

        #Collumns'names:
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(QtGui.QApplication.translate("MainWindow", "Α.Μ.", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(QtGui.QApplication.translate("MainWindow", "Ημερομηνία Δικάσιμου", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(QtGui.QApplication.translate("MainWindow", "Αριθμός Πινακίου", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(QtGui.QApplication.translate("MainWindow", "Ονοματεπώνυμο", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(QtGui.QApplication.translate("MainWindow", "Όνομα Πατρός", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText(QtGui.QApplication.translate("MainWindow", "Όνομα Μητρός", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(6)
        item.setText(QtGui.QApplication.translate("MainWindow", "Ημερομηνία Γέννησης", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(7)
        item.setText(QtGui.QApplication.translate("MainWindow", "Τόπος Γέννησης", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(8)
        item.setText(QtGui.QApplication.translate("MainWindow", "Εθνικότητα", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(9)
        item.setText(QtGui.QApplication.translate("MainWindow", "Διεύθυνση Κατοικίας", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(10)
        item.setText(QtGui.QApplication.translate("MainWindow", "Τηλέφωνο", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(11)
        item.setText(QtGui.QApplication.translate("MainWindow", "Επάγγελμα-Ιδιότητα", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(12)
        item.setText(QtGui.QApplication.translate("MainWindow", "Πράξη", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(13)
        item.setText(QtGui.QApplication.translate("MainWindow", "Ημερομηνία Τέλεσης", None, QtGui.QApplication.UnicodeUTF8))
        item = self.tableWidget.horizontalHeaderItem(14)
        item.setText(QtGui.QApplication.translate("MainWindow", "Τόπος Τέλεσης", None, QtGui.QApplication.UnicodeUTF8))

        #menubar:
        self.menubar = QtGui.QMenuBar(self)
        self.menubar.setEnabled(True)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menuFile = self.menubar.addMenu("&File")
        self.menuFile.setSizeIncrement(QtCore.QSize(0, 0))
        self.menuEdit = self.menubar.addMenu("&Edit")
        self.setMenuBar(self.menubar)
        self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8))
        self.menuEdit.setTitle(QtGui.QApplication.translate("MainWindow", "Edit", None, QtGui.QApplication.UnicodeUTF8)) 

        #Creating Action filenewchild:
        self.filenewchild = self.createAction("&Εισαγωγή Ανηλίκου", self.doupdate, "Ctrl+C", "" ,"Εισαγωγή Δεδομέων Ανηλίκου")
        self.menuFile.addAction(self.filenewchild)
        self.filenewchild.setText(QtGui.QApplication.translate("MainWindow", "Εισαγωγή Ανηλίκου", None, QtGui.QApplication.UnicodeUTF8))

        #Adding objects from lists to the Table Widget:
        r=0
        c=0
        for x in children:
            for i in x:
                newItem = QtGui.QTableWidgetItem(i)
                self.tableWidget.setItem(r, c, newItem)
                r += 1
            r = 0
            c += 1


    # Growing rows while scrolling down....
    def scrollbarChanged(self, val):
        bar = self.vBar
        minVal, maxVal = bar.minimum(), bar.maximum()
        avg = (minVal+maxVal)/2
        rowCount = self.tableWidget.rowCount()
        if val > self._vBar_lastVal and val >= avg:
            self.tableWidget.insertRow(rowCount)
        elif val < self._vBar_lastVal:
            lastRow = rowCount-30
            empty = True
            for col in xrange(self.tableWidget.columnCount()):
                item = self.tableWidget.item(lastRow, col)
                if item and item.text():
                    empty=False
                    break
            if empty:
                self.tableWidget.removeRow(lastRow)
        self._vBar_lastVal = val    


    #A function to help us create Actions faster:
    def createAction(self,text, slot=None, shortcut=None, icon=None,
                     tip=None, checkable=False, signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action    


    #A function that updates the table:
    def updatetable(self):
        self.tableWidget.clear()
        r=0
        c=0
        for x in children:
            for i in x:
                newItem = QtGui.QTableWidgetItem(i)
                self.tableWidget.setItem(r, c, newItem)
                r += 1
            r = 0
            c += 1    


    #Handles NewChildDlg actions:
    def doupdate(self):
        newchilddlg.main()
        d = NewChildDlg(self)
        if d.accept():
            text = NewChildDlg.text()
            am.append(text)
            self.updatetable()


#Main loop:
if __name__ == '__main__':
    app = QApplication(sys.argv)
    myapp = MainWindow()
    myapp.show()
    sys.exit(app.exec_())

newchilddlg.py:

# -*- coding: utf-8 -*-
#imports:
from PyQt4 import QtCore, QtGui
import sys
from PyKDE4.kdeui import KDateComboBox
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import program
from program import *


#NewChildDialog Class:
class NewChildDlg(QDialog):


    #__init__ function:
    def __init__(self, parent=None):
       super(NewChildDlg, self).__init__(parent)
       self.resize(400, 600)
       self.lineEdit = QtGui.QLineEdit(self)
       self.lineEdit.setGeometry(QtCore.QRect(160, 20, 211, 23))
       self.lineEdit.editingFinished.connect(self.amlist)
       self.kdatecombobox = KDateComboBox(self)
       self.kdatecombobox.setGeometry(QtCore.QRect(160, 50, 211, 23))
       self.lineEdit2 = QtGui.QLineEdit(self)
       self.lineEdit2.setGeometry(QtCore.QRect(160, 80, 211, 23))
       self.lineEdit3 = QtGui.QLineEdit(self)
       self.lineEdit3.setGeometry(QtCore.QRect(160, 110, 211, 23))
       self.lineEdit4 = QtGui.QLineEdit(self)
       self.lineEdit4.setGeometry(QtCore.QRect(160, 140, 211, 23))
       self.lineEdit5 = QtGui.QLineEdit(self)
       self.lineEdit5.setGeometry(QtCore.QRect(160, 170, 211, 23))
       self.kdatecombobox2 = KDateComboBox(self)
       self.kdatecombobox2.setGeometry(QtCore.QRect(160, 200, 211, 23))
       self.lineEdit6 = QtGui.QLineEdit(self)
       self.lineEdit6.setGeometry(QtCore.QRect(160, 230, 211, 23))
       self.lineEdit7 = QtGui.QLineEdit(self)
       self.lineEdit7.setGeometry(QtCore.QRect(160, 260, 211, 23))
       self.lineEdit8 = QtGui.QLineEdit(self)
       self.lineEdit8.setGeometry(QtCore.QRect(160, 290, 211, 23))
       self.lineEdit9 = QtGui.QLineEdit(self)
       self.lineEdit9.setGeometry(QtCore.QRect(160, 320, 211, 23))
       self.lineEdit10 = QtGui.QLineEdit(self)
       self.lineEdit10.setGeometry(QtCore.QRect(160, 350, 211, 23))
       self.lineEdit11 = QtGui.QLineEdit(self)
       self.lineEdit11.setGeometry(QtCore.QRect(160, 380, 211, 23))
       self.kdatecombobox3 = KDateComboBox(self)
       self.kdatecombobox3.setGeometry(QtCore.QRect(160, 410, 211, 23))
       self.lineEdit12 = QtGui.QLineEdit(self)
       self.lineEdit12.setGeometry(QtCore.QRect(160, 440, 211, 23))
       self.pushButton = QtGui.QPushButton(self)
       self.pushButton.setGeometry(QtCore.QRect(90, 530, 211, 40))
       self.pushButton.clicked.connect(self.addtolists)
       self.label = QtGui.QLabel(self)
       self.label.setGeometry(QtCore.QRect(20, 20, 211, 23))
       self.label2 = QtGui.QLabel(self)
       self.label2.setGeometry(QtCore.QRect(20, 50, 211, 23))
       self.label3 = QtGui.QLabel(self)
       self.label3.setGeometry(QtCore.QRect(20, 80, 211, 23))
       self.label4 = QtGui.QLabel(self)
       self.label4.setGeometry(QtCore.QRect(20, 110, 211, 23))
       self.label5 = QtGui.QLabel(self)
       self.label5.setGeometry(QtCore.QRect(20, 140, 211, 23))
       self.label6 = QtGui.QLabel(self)
       self.label6.setGeometry(QtCore.QRect(20, 170, 211, 23))
       self.label7 = QtGui.QLabel(self)
       self.label7.setGeometry(QtCore.QRect(20, 200, 211, 23))
       self.label8 = QtGui.QLabel(self)
       self.label8.setGeometry(QtCore.QRect(20, 230, 211, 23))
       self.label9 = QtGui.QLabel(self)
       self.label9.setGeometry(QtCore.QRect(20, 260, 211, 23))
       self.label10 = QtGui.QLabel(self)
       self.label10.setGeometry(QtCore.QRect(20, 290, 211, 23))
       self.label11 = QtGui.QLabel(self)
       self.label11.setGeometry(QtCore.QRect(20, 320, 211, 23))
       self.label12 = QtGui.QLabel(self)
       self.label12.setGeometry(QtCore.QRect(20, 350, 211, 23))
       self.label13 = QtGui.QLabel(self)
       self.label13.setGeometry(QtCore.QRect(20, 380, 211, 23))
       self.label14 = QtGui.QLabel(self)
       self.label14.setGeometry(QtCore.QRect(20, 410, 211, 23))
       self.label15 = QtGui.QLabel(self)
       self.label15.setGeometry(QtCore.QRect(20, 440, 211, 23))

       self.setWindowTitle(QtGui.QApplication.translate("Form", "Εισαγωγή Ανηλίκου", None, QtGui.QApplication.UnicodeUTF8))
       self.label.setText(QtGui.QApplication.translate("Form", "Α.Μ.:", None, QtGui.QApplication.UnicodeUTF8))
       self.label2.setText(QtGui.QApplication.translate("Form", "Ημερομηνία Δικασίμου:", None, QtGui.QApplication.UnicodeUTF8))
       self.label3.setText(QtGui.QApplication.translate("Form", "Αριθμός Πινακίου:", None, QtGui.QApplication.UnicodeUTF8))
       self.label4.setText(QtGui.QApplication.translate("Form", "Ονοματεπώνυμο:", None, QtGui.QApplication.UnicodeUTF8))
       self.label5.setText(QtGui.QApplication.translate("Form", "Όνομα Πατρός:", None, QtGui.QApplication.UnicodeUTF8))
       self.label6.setText(QtGui.QApplication.translate("Form", "Όνομα Μητρός:", None, QtGui.QApplication.UnicodeUTF8))
       self.label7.setText(QtGui.QApplication.translate("Form", "Ημερομηνία Γέννησης:", None, QtGui.QApplication.UnicodeUTF8))
       self.label8.setText(QtGui.QApplication.translate("Form", "Τόπος Γέννησης:", None, QtGui.QApplication.UnicodeUTF8))
       self.label9.setText(QtGui.QApplication.translate("Form", "Εθνικότητα:", None, QtGui.QApplication.UnicodeUTF8))
       self.label10.setText(QtGui.QApplication.translate("Form", "Διεύθυνση Κατοικίας:", None, QtGui.QApplication.UnicodeUTF8))
       self.label11.setText(QtGui.QApplication.translate("Form", "Τηλέφωνο:", None, QtGui.QApplication.UnicodeUTF8))
       self.label12.setText(QtGui.QApplication.translate("Form", "Επάγγελμα-Ιδιότητα:", None, QtGui.QApplication.UnicodeUTF8))
       self.label13.setText(QtGui.QApplication.translate("Form", "Πράξη:", None, QtGui.QApplication.UnicodeUTF8))
       self.label14.setText(QtGui.QApplication.translate("Form", "Ημερομηνία Τέλεσης:", None, QtGui.QApplication.UnicodeUTF8))
       self.label15.setText(QtGui.QApplication.translate("Form", "Τόπος Τέλεσης:", None, QtGui.QApplication.UnicodeUTF8))
       self.pushButton.setText(QtGui.QApplication.translate("Form", "Εισαγωγή", None, QtGui.QApplication.UnicodeUTF8))

    def amlist(self):
        self.text = str(self.lineEdit.text())

    def addtolists(self):
        dialog.accept()        


#Main loop:        
def main():
    global dialog
    dialog = NewChildDlg()
    dialog.show()
    dialog.exec_()
4

1 回答 1

11

具体错误相关问题

删除 update2 方法上的 classmethod 装饰器。它使“自我”变成类对象,并且您的类上没有 tableWidget 属性。只有你的小部件。这里的装饰器没有用。

一般设计和基本问题

此代码存在一些严重的重大基本问题。我意识到你是新人并且正在学习,所以你现在解决这些问题更加重要。这是一本很棒的书,使用 Python 和 Qt 进行快速 GUI 编程,对于学习 PyQt,我赞不绝口

您在这里所做的是获取由 Qt Designer 生成的 UI 设计文件,并对其进行编辑以将您的逻辑插入setupUi方法中。关于这个 ui 文件,您需要了解的是它创建了包含要应用于您自己的类的小部件设置代码的通用类。您在底部有概念的那一部分,您可以在其中创建一个新的 QMainWindow 然后调用setupUi它。您不应该做的是创建大量全局变量或在这些 UI 设置类中添加额外的方法和逻辑。你也有一个错误的例子@classmethod

PyQt 中的对象关系通常是这样工作的……父类可以有属性和子小部件。子小部件可以具有属性,并且通常不知道它们的父母。

如何正确设置此 QMainWindow 的一个示例是首先将该 UI 自动生成代码保存在其自己的文件中(myappUI.py或类似的文件)。然后您将为您的 QMainWindow 创建一个子类,其中将包含您的自定义方法和数据属性:

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

        # create instance attributes to store data
        ...
        self.mothersname = []
        self.birthday = []
        self.placeofbirth = []
        self.nationality = []
        self.address = []
        ...

        r=0
        c=0
        for x in children:
            for i in x:
                newItem = QtGui.QTableWidgetItem(i)
                self.tableWidget.setItem(r, c, newItem)
                r += 1
            r = 0
            c += 1

    def newFile(self):
        ...

    def openFile(self):
        ...

    def Quit(self):
        # Dont force the exit of the app like this.
        # Just close the main window
        # sys.exit(app.exec_())

    # this was in no way a classmethod      
    # @classmethod
    def update2(self): 
        ...

    def actionewchild(self):
        ...
        # if you want to create a form dialog on the fly
        # and kill it after you get results
        form = Form(parent=self)
        form.exec_()

    def lists(self):
        ...

class Form(QtGui.QDialog, Ui_Form):

    def __init__(self, *args, **kwargs):
        super(Form, self).__init__(*args, **kwargs)
        self.setupUi(self)

    def amlist(self):
        ...

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

这只是一个粗略的大纲,说明如何将其重组为两个类,每个类都继承自他们的 UI 设计。那些大量的全局变量可能会作为实例属性移动到您的 MainWindow 中。不要使用全局变量。

我之所以采用这种方法,建议您彻底重组,是因为您正走在一条非常混乱且可能令人沮丧的道路上。事情不会像您期望的那样工作,您会发现自己经常在这里发布关于为什么会发生这种情况的帖子。如果您花时间阅读我建议的那本书,您将获得更好的体验。

更新 #1:匹配您的代码更新

主窗口和对话框之间的概念是倒退的。您的主窗口将操作连接到对话框模块中的功能以启动它并完成工作。真正应该发生的是你的主窗口连接到它自己的方法。此方法将启动对话框,获取结果并自行修改。

def addtolists(self):
    program.am.append(text)
    instance = MainWindow()
    instance.updatetable()
    dialog.close()  

您的对话框中有该代码。首先,像这样调用 MainWindow 不会让您获得实例。它将尝试创建第二个主窗口小部件。不要尝试获取对父级的引用并对其进行修改。孩子们不应该知道正在使用它的父母。就您所知,您可能会在不同的地方使用此对话框。

# this is just a pseudo example of the right direction.
# A method in your MainWindow, starting the child dialog,
# waiting on its results, and updating itself.
def showDialog(self):
    d = MyDialog(self)
    if d.exec_():
        self.updateStuff(d.values)

myAction.triggered.connect(self.showDialog)

至于全局变量......您的应用程序设计中不应该需要一个全局变量。它们适用于您知道需要它们的特殊情况。我想说的是,如果您现在使用全局变量,您可能做错了。原因是您使用它们在不同方向传递数据,而不是遵循父子关系,或通过信号/插槽传递数据。如果父级启动子小部件,它将了解子级并能够调用方法或从中获取值。

更新 #2:匹配您的代码更新

从主窗口创建对话框有点偏离。它应该是这样的:

def doupdate(self):
    d = NewChildDlg(self)
    # exec_ shows the dialog modally
    if d.exec_():
        # your dialog didn't have a pre-initialized
        # `text` attribute so it was not safe to assume
        text = d.lineEdit.text()
        # stop using globals. use attributes
        self.am.append(text)
        self.updatetable()

对于全球...再次停止使用它们。将它们移动到您的主窗口类中:

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.am = []
        self.courtdate = []
        self.board_number = []

您的对话框类中的这一部分是错误的:

    def addtolists(self):
        # why use a global here? dialog == self
        # self.accept()
        dialog.accept()        

# you don't need a top level function that
# maintains a global instance and creates the dialog
# It should be the callers responsibility
def main():
    global dialog
    dialog = NewChildDlg()
    dialog.show()
    dialog.exec_()

最后,只是对您的导入语句的评论......您无需先导入模块即可导入该模块的成员:

# either you need the newchilddlg namespace
# or you only want the members...
# newchilddlg.NewChildDlg  vs  NewChildDlg
import newchilddlg
from newchilddlg import *

为了帮助您更多,我在这里发布了您的主窗口代码的清理版本:http: //pastebin.com/9b8gcGhU

于 2012-07-14T15:19:05.990 回答