代码之家  ›  专栏  ›  技术社区  ›  lloydyu24

无法关闭Python PyQt4上的对话框

  •  0
  • lloydyu24  · 技术社区  · 8 年前

    我的程序有一个主窗口,其中包含我的库存系统。我添加了一个对话框窗口,当我单击“添加项目”时会弹出。我能够成功打开对话框窗口,但似乎无法关闭它。

    自己关闭() . 它只会关闭我为防止意外退出而创建的消息框,并且不会关闭对话框窗口,除非您使用IDE或任务管理器结束它。

    以下是我的代码片段:

    主要的py公司

    class Main(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
    
            self.db = Database()
            self.model = Model(self)
            self.ui = MainWindow_ui()
            self.ui.setupUi(self)
            self.window = Ui_Dialog()
    
            self.ui.addItem.clicked.connect(lambda : self.start_Form())
    
        def start_Form(self):
            window = QtGui.QDialog()
            self.window.setupUi(window)
            self.window.show()
    
    def main():
        app = QtGui.QApplication(sys.argv)
        window = Main()
        window.showMaximized()
        sys.exit(app.exec_())
    
    if __name__ == "__main__":
        main()
    

    附加项。py(包含对话框窗口代码)

    def getNumber():
        conn = sqlite3.connect('inventory.db')
        c = conn.cursor()
        c.execute('SELECT seq FROM sqlite_sequence')
        itemNumber = c.fetchone()[0]
        return int(itemNumber) + 1
    
    class Ui_Dialog(QtGui.QDialog):
        def __init__(self):
            QtGui.QDialog.__init__(self)
            self.setupUi(self)
    
        def setupUi(self, Dialog):
            Dialog.setObjectName(_fromUtf8("Dialog"))
            Dialog.resize(413, 382)
    
            self.buttonBox = QtGui.QDialogButtonBox(Dialog)
            self.buttonBox.setStandardButtons(
                QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Reset)
            self.buttonBox.accepted.connect(self.accept)
            self.buttonBox.rejected.connect(self.reject)
    
        def retranslateUi(self, Dialog):    
            self.itemCode.setText(str(getNumber()))
    
        def accept(self):
            row = self.mapper.currentIndex()
            self.mapper.submit()
            self.main.model.insertRow(row)
            self.mapper.setCurrentIndex(row)
    
            self.close()
    
        def reject(self):
            ret = QtGui.QMessageBox.question(None, 'Close request', 'Are you sure you want to quit?',
                                             QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
            if ret == QtGui.QMessageBox.Yes:
                self.close()
            else:
                pass
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   ekhumoro    8 年前

    你的 accept() reject() close() 反过来,只需再次调用这些方法。重写虚拟方法时,应使用调用基类实现 super :

    class Ui_Dialog(QtGui.QDialog):
        ...
    
        def accept(self):
            ...
            super(Ui_Dialog, self).accept()  
    
        def reject(self):
            ...
            if ret == QtGui.QMessageBox.Yes:
                super(Ui_Dialog, self).reject()