3

He creado una ventana principal, en la barra de menú dentro del botón definir hay un botón de datos de entrada el cual programé para que me abra una subventana, si doy clic en ‘+’ añado datos.

El problema es que al darle al botón guardar mi tabla no guarda los datos, ya que al volver a dar clic en datos de entrada mi tabla aparece vacía y se pierden todos mis datos.

El problema en sí está dentro de la función guardar de mi subclase ventana.

Otra cosa: ¿existe alguna forma de centrar horizontal y verticalmente el texto de la tabla? Soy relativamente nuevo en este tema, muchas gracias.

Archivos.ui: archivos de ventana y subventana

Nota: Para ejecutar la interfaz deben hacerlo desde el módulo main.

CLASE PRINCIPAL 'main' (Nota: este archivo está fuera del paquete que contiene a la clase subventana)

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QMdiSubWindow
from PyQt5.uic import loadUi
from src_gui.subventana_datosEntrada import subwindow_datosEntrada

class window_inicial(QMainWindow):
    def __init__(self, parent=None):
        super(window_inicial,self).__init__( parent)   
        loadUi('Gui/ventana_inicio.ui', self) 
        self.actionDatosEntrada.triggered.connect(self.f_datosEntrada)

        self.ventanas = [0]
        self.datos_generales = [[],[]]

    def f_datosEntrada(self):
        if self.ventanas[0] == 0:
            winw = QMdiSubWindow()
            winw.setWidget(subwindow_datosEntrada(self))
            self.contenedor_MesaTrabajo.addSubWindow(winw)
            winw.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = window_inicial()
    widget.show()
    sys.exit(app.exec_())

CLASE DE LA SUBVENTANA

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QComboBox, QTableWidgetItem, QMessageBox
from PyQt5.uic import loadUi

class subwindow_datosEntrada(QMainWindow):

    def __init__(self, parent=None):    
        super(subwindow_datosEntrada,self).__init__( parent)        
        loadUi('Gui/subventana_datos2.ui', self) 

        self.parent = parent        
        self.parent.ventanas[0] = 1

        # Botones
        self.btn_mas.clicked.connect(self.mas)
        self.btn_menos.clicked.connect(self.menos)
        self.btn_AnalisisDiseno.clicked.connect(self.guardar)

    def mas(self):
        nuevo = self.table_datosEntrada.rowCount()
        self.table_datosEntrada.insertRow(nuevo)      

        for row in range(self.table_datosEntrada.rowCount()-1, self.table_datosEntrada.rowCount(),1):
            c1 = QComboBox()
            c1.addItems(['C', 'V'])
            c2 = QComboBox()
            c2.addItems(['H', 'B', 'P'])
            item = QTableWidgetItem(str(self.table_datosEntrada.rowCount()))

            self.table_datosEntrada.setCellWidget(row,1,c1) #--> Agrego el "ComboBox" en la columna correspondiente
            self.table_datosEntrada.setCellWidget(row,12,c2) #--> Agrego el "ComboBox" en la columna correspondiente
            self.table_datosEntrada.setItem(row ,0, item)    

    def menos(self):
        nuevo = self.table_datosEntrada.rowCount()
        self.table_datosEntrada.removeRow(nuevo-1)

    def guardar(self):
        try:
            self.parent.datos_generales[1] = []
            for i in range(self.table_datosEntrada.rowCount()):
                self.parent.datos_generales[1].append(['','','','','','','','','','','','','','','','','','','','','','',''])
                self.parent.datos_generales[1][i][0] = int(self.table_datosEntrada.item(i, 0).text())
                self.parent.datos_generales[1][i][1] = self.table_datosEntrada.cellWidget(i, 1).currentText()
                self.parent.datos_generales[1][i][2] = int(self.table_datosEntrada.item(i, 2).text())
                self.parent.datos_generales[1][i][3] = int(self.table_datosEntrada.item(i, 3).text())
                self.parent.datos_generales[1][i][4] = int(self.table_datosEntrada.item(i, 4).text())
                self.parent.datos_generales[1][i][5] = int(self.table_datosEntrada.item(i, 5).text())
                self.parent.datos_generales[1][i][6] = int(self.table_datosEntrada.item(i, 6).text())
                self.parent.datos_generales[1][i][7] = int(self.table_datosEntrada.item(i, 7).text())
                self.parent.datos_generales[1][i][8] = float(self.table_datosEntrada.item(i, 8).text())
                self.parent.datos_generales[1][i][9] = float(self.table_datosEntrada.item(i, 9).text())
                self.parent.datos_generales[1][i][10] = float(self.table_datosEntrada.item(i, 10).text())
                self.parent.datos_generales[1][i][11] = float(self.table_datosEntrada.item(i, 11).text())
                self.parent.datos_generales[1][i][12] = self.table_datosEntrada.cellWidget(i, 12).currentText()
                self.parent.datos_generales[1][i][13] = int(self.table_datosEntrada.item(i, 13).text())
                self.parent.datos_generales[1][i][14] = int(self.table_datosEntrada.item(i, 14).text())
                self.parent.datos_generales[1][i][15] = int(self.table_datosEntrada.item(i, 15).text())
                self.parent.datos_generales[1][i][16] = int(self.table_datosEntrada.item(i, 16).text())
                self.parent.datos_generales[1][i][17] = int(self.table_datosEntrada.item(i, 17).text())
                self.parent.datos_generales[1][i][18] = int(self.table_datosEntrada.item(i, 18).text())
                self.parent.datos_generales[1][i][19] = int(self.table_datosEntrada.item(i, 19).text())
                self.parent.datos_generales[1][i][20] = int(self.table_datosEntrada.item(i, 20).text())
                self.parent.datos_generales[1][i][21] = int(self.table_datosEntrada.item(i, 21).text())
                self.parent.datos_generales[1][i][22] = int(self.table_datosEntrada.item(i, 22).text())

                self.parent.ventanas[0] = 0
                self.close()        
        except ValueError:
            QMessageBox.warning(self, 'Aviso', 'Valores ingresados no númericos, corregir')

        except AttributeError:
            QMessageBox.warning(self, 'Aviso', 'Valores ingresados no númericos, corregir')


    def closeEvent(self, event):
        self.parent.ventanas[0] = 0

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = subwindow_datosEntrada()
    widget.show()
    sys.exit(app.exec_())

1 respuesta 1

2

No hay ningún problema con tu método guardar, el problema es que cuando vuelves a llamar a la ventana creas una nueva instancia de subwindow_datosEntrada con una nueva tabla (vacía por tanto), pero en ningún momento cargas los datos de la lista en la nueva tabla.

Yo de todas formas no me complicaría, simplemente reutiliza la instancia anterior y vuelve a mostrarla:

main.py
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QMdiSubWindow
from PyQt5.uic import loadUi
from src_gui.subventana_datosEntrada import SubwindowDatosEntrada


class WindowInicial(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        loadUi('Gui/ventana_inicio.ui', self)
        self.actionDatosEntrada.triggered.connect(self.datos_entrada)

        self.ventanas = [None]
        self.datos_generales = [[], []]
        self.winw = None

    def datos_entrada(self):
        print(self.datos_generales[1])
        if self.ventanas[0] is None:
            winw = QMdiSubWindow()
            widget = SubwindowDatosEntrada()
            widget.table_list = self.datos_generales[1]
            winw.setWidget(widget)
            self.contenedor_MesaTrabajo.addSubWindow(winw)
            self.ventanas[0] = winw
            winw.show()

        else:
            winw = self.ventanas[0]
            winw.widget().show()
            winw.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = WindowInicial()
    widget.show()
    sys.exit(app.exec_())
subventana_datosEntrada.py
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QComboBox, QTableWidgetItem, QMessageBox
from PyQt5.uic import loadUi
from PyQt5 import QtCore


class SubwindowDatosEntrada(QMainWindow):

    def __init__(self, root=None):
        super().__init__(root)
        loadUi('Gui/subventana_datos2.ui', self)
        self.root = root

        # Botones
        self.btn_mas.clicked.connect(self.mas)
        self.btn_menos.clicked.connect(self.menos)
        self.btn_AnalisisDiseno.clicked.connect(self.guardar)

        self.table_list = []

    def mas(self):
        nuevo = self.table_datosEntrada.rowCount()
        self.table_datosEntrada.insertRow(nuevo)

        for row in range(
                self.table_datosEntrada.rowCount() - 1,
                self.table_datosEntrada.rowCount(), 1):
            c1 = QComboBox()
            c1.addItems(['C', 'V'])
            c2 = QComboBox()
            c2.addItems(['H', 'B', 'P'])
            item = QTableWidgetItem(str(self.table_datosEntrada.rowCount()))

            self.table_datosEntrada.setCellWidget(row, 1, c1)
            self.table_datosEntrada.setCellWidget(row, 12, c2)
            self.table_datosEntrada.setItem(row, 0, item)

    def menos(self):
        nuevo = self.table_datosEntrada.rowCount()
        self.table_datosEntrada.removeRow(nuevo - 1)

    def guardar(self):
        try:
            self.table_list.clear()
            table = self.table_datosEntrada
            for i in range(table.rowCount()):
                self.table_list.append([None] * 23)
                row = self.table_list[i]
                row[0] = int(table.item(i, 0).text())
                row[1] = table.cellWidget(i, 1).currentText()
                row[2] = int(table.item(i, 2).text())
                row[3] = int(table.item(i, 3).text())
                row[4] = int(table.item(i, 4).text())
                row[5] = int(table.item(i, 5).text())
                row[6] = int(table.item(i, 6).text())
                row[7] = int(table.item(i, 7).text())
                row[8] = float(table.item(i, 8).text())
                row[9] = float(table.item(i, 9).text())
                row[10] = float(table.item(i, 10).text())
                row[11] = float(table.item(i, 11).text())
                row[12] = table.cellWidget(i, 12).currentText()
                row[13] = int(table.item(i, 13).text())
                row[14] = int(table.item(i, 14).text())
                row[15] = int(table.item(i, 15).text())
                row[16] = int(table.item(i, 16).text())
                row[17] = int(table.item(i, 17).text())
                row[18] = int(table.item(i, 18).text())
                row[19] = int(table.item(i, 19).text())
                row[20] = int(table.item(i, 20).text())
                row[21] = int(table.item(i, 21).text())
                row[22] = int(table.item(i, 22).text())

            self.parent().close()

        except (ValueError, AttributeError):
            QMessageBox.warning(
                self, 'Aviso', 'Valores ingresados no númericos, corregir'
                )


if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = SubwindowDatosEntrada()
    widget.show()
    sys.exit(app.exec_())
1
  • Es verdad, el problema es la tabla, muchas gracias.
    – Daniel
    el 12 abr. 2020 a las 2:52

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.