Esempio n. 1
0
class widgetReacciones(QtWidgets.QWidget):
    """Widget con la tabla de reacciones y los botones para modificar la lista de reacciones"""
    changed = QtCore.pyqtSignal()
    reacciones = []
    reaccion = None
    activo = None
    ajuste = None

    def __init__(self, parent=None):
        super(widgetReacciones, self).__init__(parent)
        self.indices, self.nombres, M = getComponents()
        gridLayout = QtWidgets.QGridLayout(self)

        self.TablaReacciones = Tabla(
            5,
            horizontalHeader=[
                QtWidgets.QApplication.translate("pychemqt", "Reaction"),
                "ΔHr, %s" % unidades.MolarEnthalpy(None).text(),
                QtWidgets.QApplication.translate("pychemqt", "Type"),
                QtWidgets.QApplication.translate("pychemqt", "Phase"),
                QtWidgets.QApplication.translate("pychemqt", "Description")
            ],
            dinamica=False,
            verticalHeader=True,
            orientacion=QtCore.Qt.AlignLeft)
        self.TablaReacciones.setMinimumWidth(500)
        self.TablaReacciones.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)
        self.TablaReacciones.setSelectionMode(
            QtWidgets.QAbstractItemView.SingleSelection)
        self.TablaReacciones.horizontalHeader().setStretchLastSection(True)
        self.TablaReacciones.setEditTriggers(
            QtWidgets.QAbstractItemView.NoEditTriggers)
        self.TablaReacciones.itemSelectionChanged.connect(
            self.actualizarBotones)
        gridLayout.addWidget(self.TablaReacciones, 1, 1, 6, 4)

        self.botonAbrir = QtWidgets.QPushButton(
            QtGui.QIcon(
                QtGui.QPixmap(os.environ["pychemqt"] +
                              "/images/button/fileOpen.png")),
            QtWidgets.QApplication.translate("pychemqt", "Open"))
        self.botonAbrir.clicked.connect(self.botonAbrirClicked)
        gridLayout.addWidget(self.botonAbrir, 1, 5)
        self.botonGuardar = QtWidgets.QPushButton(
            QtGui.QIcon(
                QtGui.QPixmap(os.environ["pychemqt"] +
                              "/images/button/fileSave.png")),
            QtWidgets.QApplication.translate("pychemqt", "Save"))
        self.botonGuardar.clicked.connect(self.botonGuardarClicked)
        self.botonGuardar.setSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                        QtWidgets.QSizePolicy.Fixed)
        self.botonGuardar.setEnabled(False)
        gridLayout.addWidget(self.botonGuardar, 2, 5)

        self.botonNew = QtWidgets.QPushButton(
            QtGui.QIcon(
                QtGui.QPixmap(os.environ["pychemqt"] +
                              "/images/button/fileNew.png")),
            QtWidgets.QApplication.translate("pychemqt", "New"))
        self.botonNew.clicked.connect(self.botonNewClicked)
        gridLayout.addWidget(self.botonNew, 3, 5)
        self.botonEdit = QtWidgets.QPushButton(
            QtGui.QIcon(
                QtGui.QPixmap(os.environ["pychemqt"] +
                              "/images/button/editor.png")),
            QtWidgets.QApplication.translate("pychemqt", "Edit"))
        self.botonEdit.setEnabled(False)
        self.botonEdit.setCheckable(True)
        self.botonEdit.clicked.connect(self.botonEditClicked)
        gridLayout.addWidget(self.botonEdit, 4, 5)
        self.botonDelete = QtWidgets.QPushButton(
            QtGui.QIcon(
                QtGui.QPixmap(os.environ["pychemqt"] +
                              "/images/button/editDelete.png")),
            QtWidgets.QApplication.translate("pychemqt", "Delete"))
        self.botonDelete.setEnabled(False)
        self.botonDelete.clicked.connect(self.botonDeleteClicked)
        gridLayout.addWidget(self.botonDelete, 5, 5)
        self.botonClear = QtWidgets.QPushButton(
            QtGui.QIcon(
                QtGui.QPixmap(os.environ["pychemqt"] +
                              "/images/button/clear.png")),
            QtWidgets.QApplication.translate("pychemqt", "Clear"))
        self.botonClear.clicked.connect(self.botonClearClicked)
        gridLayout.addWidget(self.botonClear, 6, 5)
        gridLayout.addItem(
            QtWidgets.QSpacerItem(10, 10, QtWidgets.QSizePolicy.Expanding,
                                  QtWidgets.QSizePolicy.Expanding), 10, 1)

    def actualizarBotones(self, bool=True):
        self.botonEdit.setEnabled(bool)
        self.botonDelete.setEnabled(bool)

    def botonAbrirClicked(self):
        fname = str(
            QtWidgets.QFileDialog.getOpenFileName(
                self,
                QtWidgets.QApplication.translate("pychemqt",
                                                 "Open reaction file"), "./",
                QtWidgets.QApplication.translate("pychemqt", "reaction file") +
                " (*.rec);;" +
                QtWidgets.QApplication.translate("pychemqt", "All files") +
                " (*.*)")[0])
        if fname:
            with open(fname, "r") as archivo:
                reacciones = pickle.load(archivo)
            print(reacciones)
            self.reacciones = reacciones
            self.botonGuardar.setEnabled(True)
            for fila, reaccion in enumerate(reacciones):
                self.TablaReacciones.addRow()
                self.TablaReacciones.setValue(fila, 0, reaccion.text)
                self.TablaReacciones.setValue(fila, 1,
                                              "%0.4e" % reaccion.Hr.config(),
                                              QtCore.Qt.AlignRight)
                self.TablaReacciones.setValue(
                    fila, 2,
                    str(reaccion.tipo + 1) + " - " +
                    reaction.Reaction.TEXT_TYPE[reaccion.tipo])
                self.TablaReacciones.setValue(
                    fila, 3, reaction.Reaction.TEXT_PHASE[reaccion.fase])
                self.TablaReacciones.item(
                    fila, 4).setFlags(QtCore.Qt.ItemIsEditable
                                      | QtCore.Qt.ItemIsEnabled
                                      | QtCore.Qt.ItemIsSelectable)
            for i in range(4):
                self.TablaReacciones.resizeColumnToContents(i)
        self.changed.emit()

    def botonGuardarClicked(self):
        fname = str(
            QtWidgets.QFileDialog.getSaveFileName(
                self,
                QtWidgets.QApplication.translate("pychemqt",
                                                 "Save reaction to file"),
                "./",
                QtWidgets.QApplication.translate("pychemqt", "reaction file") +
                " (*.rec)")[0])
        if fname:
            if fname.split(".")[-1] != "rec":
                fname += ".rec"
            pickle.dump(self.reacciones, open(fname, "w"))

    def botonNewClicked(self):
        dialog = UI_reacciones(parent=self)
        if dialog.exec_():
            pass

    def botonEditClicked(self, bool):
        if bool:
            indice = self.TablaReacciones.currentRow()
            reaccion = self.reacciones[indice]
            dialogo = UI_reacciones(reaccion, self)
            dialogo.exec_()


#            self.rellenar(self.reaccion)
#            self.activo=indice
        else:
            self.botonAddClicked(self.activo, False)
            self.reacciones[self.activo] = self.reaccion
            self.TablaReacciones.setCurrentCell(self.activo, 0)
            self.activo = -1
            self.changed.emit()

        self.botonNew.setEnabled(not bool)
        self.botonDelete.setEnabled(not bool)
        self.botonClear.setEnabled(not bool)
        self.botonAdd.setEnabled(not bool)
        self.botonAbrir.setEnabled(not bool)
        self.botonGuardar.setEnabled(not bool)

    def botonDeleteClicked(self):
        indice = self.TablaReacciones.currentRow()
        self.TablaReacciones.removeRow(indice)
        del self.reacciones[indice]
        self.TablaReacciones.clearSelection()
        self.actualizarBotones(False)
        self.changed.emit()

    def botonClearClicked(self):
        if self.reacciones:
            self.reacciones = []
            self.TablaReacciones.setRowCount(0)
            self.botonGuardar.setEnabled(False)

    def botonAddClicked(self, fila, add=True):
        if add:
            fila = self.TablaReacciones.rowCount()
            self.TablaReacciones.addRow()
        self.TablaReacciones.setValue(fila, 0, self.Formula.text())
        self.TablaReacciones.setValue(fila, 1,
                                      "%0.4e" % self.Hr.value.config(),
                                      QtCore.Qt.AlignRight)
        self.TablaReacciones.setValue(
            fila, 2,
            str(self.tipo.currentIndex() + 1) + " - " +
            self.tipo.currentText())
        self.TablaReacciones.setValue(fila, 3, self.Fase.currentText())
        self.TablaReacciones.item(fila,
                                  4).setFlags(QtCore.Qt.ItemIsEditable
                                              | QtCore.Qt.ItemIsEnabled
                                              | QtCore.Qt.ItemIsSelectable)
        for i in range(4):
            self.TablaReacciones.resizeColumnToContents(i)
        self.reacciones.insert(fila, self.reaccion)
        self.botonGuardar.setEnabled(True)
        self.changed.emit()
Esempio n. 2
0
class widgetReacciones(QtWidgets.QWidget):
    """Widget con la tabla de reacciones y los botones para modificar la lista de reacciones"""
    changed = QtCore.pyqtSignal()
    reacciones=[]
    reaccion=None
    activo=None
    ajuste=None

    def __init__(self, parent=None):
        super(widgetReacciones, self).__init__(parent)
        self.indices, self.nombres, M=getComponents()
        gridLayout = QtWidgets.QGridLayout(self)

        self.TablaReacciones=Tabla(5, horizontalHeader=[QtWidgets.QApplication.translate("pychemqt", "Reaction"), "ΔHr, %s" %unidades.MolarEnthalpy(None).text(), QtWidgets.QApplication.translate("pychemqt", "Type"), QtWidgets.QApplication.translate("pychemqt", "Phase"), QtWidgets.QApplication.translate("pychemqt", "Description")], dinamica=False, verticalHeader=True, orientacion=QtCore.Qt.AlignLeft)
        self.TablaReacciones.setMinimumWidth(500)
        self.TablaReacciones.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.TablaReacciones.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
        self.TablaReacciones.horizontalHeader().setStretchLastSection(True)
        self.TablaReacciones.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.TablaReacciones.itemSelectionChanged.connect(self.actualizarBotones)
        gridLayout.addWidget(self.TablaReacciones,1,1,6,4)

        self.botonAbrir=QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(os.environ["pychemqt"]+"/images/button/fileOpen.png")), QtWidgets.QApplication.translate("pychemqt", "Open"))
        self.botonAbrir.clicked.connect(self.botonAbrirClicked)
        gridLayout.addWidget(self.botonAbrir,1,5)
        self.botonGuardar=QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(os.environ["pychemqt"]+"/images/button/fileSave.png")), QtWidgets.QApplication.translate("pychemqt", "Save"))
        self.botonGuardar.clicked.connect(self.botonGuardarClicked)
        self.botonGuardar.setSizePolicy(QtWidgets.QSizePolicy.Fixed,QtWidgets.QSizePolicy.Fixed)
        self.botonGuardar.setEnabled(False)
        gridLayout.addWidget(self.botonGuardar,2,5)

        self.botonNew=QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(os.environ["pychemqt"]+"/images/button/fileNew.png")), QtWidgets.QApplication.translate("pychemqt", "New"))
        self.botonNew.clicked.connect(self.botonNewClicked)
        gridLayout.addWidget(self.botonNew,3,5)
        self.botonEdit=QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(os.environ["pychemqt"]+"/images/button/editor.png")), QtWidgets.QApplication.translate("pychemqt", "Edit"))
        self.botonEdit.setEnabled(False)
        self.botonEdit.setCheckable(True)
        self.botonEdit.clicked.connect(self.botonEditClicked)
        gridLayout.addWidget(self.botonEdit,4,5)
        self.botonDelete=QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(os.environ["pychemqt"]+"/images/button/editDelete.png")), QtWidgets.QApplication.translate("pychemqt", "Delete"))
        self.botonDelete.setEnabled(False)
        self.botonDelete.clicked.connect(self.botonDeleteClicked)
        gridLayout.addWidget(self.botonDelete,5,5)
        self.botonClear=QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(os.environ["pychemqt"]+"/images/button/clear.png")), QtWidgets.QApplication.translate("pychemqt", "Clear"))
        self.botonClear.clicked.connect(self.botonClearClicked)
        gridLayout.addWidget(self.botonClear,6,5)
        gridLayout.addItem(QtWidgets.QSpacerItem(10,10,QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding),10,1)


    def actualizarBotones(self, bool=True):
        self.botonEdit.setEnabled(bool)
        self.botonDelete.setEnabled(bool)

    def botonAbrirClicked(self):
        fname = str(QtWidgets.QFileDialog.getOpenFileName(self, QtWidgets.QApplication.translate("pychemqt", "Open reaction file"), "./", QtWidgets.QApplication.translate("pychemqt", "reaction file")+" (*.rec);;"+QtWidgets.QApplication.translate("pychemqt", "All files")+" (*.*)")[0])
        if fname:
            with open(fname, "r") as archivo:
                reacciones=pickle.load(archivo)
            print(reacciones)
            self.reacciones=reacciones
            self.botonGuardar.setEnabled(True)
            for fila, reaccion in enumerate(reacciones):
                self.TablaReacciones.addRow()
                self.TablaReacciones.setValue(fila, 0, reaccion.text)
                self.TablaReacciones.setValue(fila, 1, "%0.4e" %reaccion.Hr.config(), QtCore.Qt.AlignRight)
                self.TablaReacciones.setValue(fila, 2, str(reaccion.tipo+1)+" - "+reaction.Reaction.TEXT_TYPE[reaccion.tipo])
                self.TablaReacciones.setValue(fila, 3, reaction.Reaction.TEXT_PHASE[reaccion.fase])
                self.TablaReacciones.item(fila, 4).setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)
            for i in range(4):
                self.TablaReacciones.resizeColumnToContents(i)
        self.changed.emit()

    def botonGuardarClicked(self):
        fname = str(QtWidgets.QFileDialog.getSaveFileName(self, QtWidgets.QApplication.translate("pychemqt", "Save reaction to file"), "./", QtWidgets.QApplication.translate("pychemqt", "reaction file")+" (*.rec)")[0])
        if fname:
            if fname.split(".")[-1]!="rec":
                fname+=".rec"
            pickle.dump(self.reacciones, open(fname, "w"))

    def botonNewClicked(self):
        dialog=UI_reacciones(parent=self)
        if dialog.exec_():
            pass


    def botonEditClicked(self, bool):
        if bool:
            indice=self.TablaReacciones.currentRow()
            reaccion=self.reacciones[indice]
            dialogo=UI_reacciones(reaccion, self)
            dialogo.exec_()
#            self.rellenar(self.reaccion)
#            self.activo=indice
        else:
            self.botonAddClicked(self.activo, False)
            self.reacciones[self.activo]=self.reaccion
            self.TablaReacciones.setCurrentCell(self.activo, 0)
            self.activo=-1
            self.changed.emit()

        self.botonNew.setEnabled(not bool)
        self.botonDelete.setEnabled(not bool)
        self.botonClear.setEnabled(not bool)
        self.botonAdd.setEnabled(not bool)
        self.botonAbrir.setEnabled(not bool)
        self.botonGuardar.setEnabled(not bool)


    def botonDeleteClicked(self):
        indice=self.TablaReacciones.currentRow()
        self.TablaReacciones.removeRow(indice)
        del self.reacciones[indice]
        self.TablaReacciones.clearSelection()
        self.actualizarBotones(False)
        self.changed.emit()

    def botonClearClicked(self):
        if self.reacciones:
            self.reacciones=[]
            self.TablaReacciones.setRowCount(0)
            self.botonGuardar.setEnabled(False)

    def botonAddClicked(self, fila, add=True):
        if add:
            fila=self.TablaReacciones.rowCount()
            self.TablaReacciones.addRow()
        self.TablaReacciones.setValue(fila, 0, self.Formula.text())
        self.TablaReacciones.setValue(fila, 1, "%0.4e" %self.Hr.value.config(), QtCore.Qt.AlignRight)
        self.TablaReacciones.setValue(fila, 2, str(self.tipo.currentIndex()+1)+" - "+self.tipo.currentText())
        self.TablaReacciones.setValue(fila, 3, self.Fase.currentText())
        self.TablaReacciones.item(fila, 4).setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)
        for i in range(4):
            self.TablaReacciones.resizeColumnToContents(i)
        self.reacciones.insert(fila, self.reaccion)
        self.botonGuardar.setEnabled(True)
        self.changed.emit()
Esempio n. 3
0
class InputTableWidget(QtWidgets.QWidget):
    """Table data input dialog"""
    def __init__(self, columnas, data=None, t=[], property=[],
                 horizontalHeader=[], title="", DIPPR=False, hasTc=0,
                 Tc=None, eq=1, unit=[], parent=None):
        """
        data: mrray with original data
        t: values for x column, generally temperature
        property: values for 2...n columns
        horizontalHeader: List with column title
        DIPPR: boolean to show DIPPR widget
        hasTc: boolean to show critical temperature (some DIPPR eq need it)
        Tc: value for critical temperature
        eq: Value for DIPPR equation
        unit: List of unidades classes for column definition
        """
        super(InputTableWidget, self).__init__(parent)
        self.columnas = columnas
        self.title = title
        self.unit = unit
        gridLayout = QtWidgets.QGridLayout(self)
        gridLayout.setContentsMargins(0, 0, 0, 0)
        openButton = QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(
            os.environ["pychemqt"]+"/images/button/fileOpen.png")), "")
        openButton.setToolTip(QtWidgets.QApplication.translate(
            "pychemqt", "Load data from a file"))
        openButton.clicked.connect(self.open)
        gridLayout.addWidget(openButton, 1, 1)
        saveButton = QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(
            os.environ["pychemqt"]+"/images/button/fileSave.png")), "")
        saveButton.setToolTip(QtWidgets.QApplication.translate(
            "pychemqt", "Save data to a file"))
        saveButton.clicked.connect(self.save)
        gridLayout.addWidget(saveButton, 1, 2)
        clearButton = QtWidgets.QPushButton(QtGui.QIcon(QtGui.QPixmap(
            os.environ["pychemqt"]+"/images/button/clear.png")), "")
        clearButton.setToolTip(QtWidgets.QApplication.translate(
            "pychemqt", "Clear data"))
        clearButton.clicked.connect(self.delete)
        gridLayout.addWidget(clearButton, 1, 3)
        gridLayout.addItem(QtWidgets.QSpacerItem(
            0, 0, QtWidgets.QSizePolicy.Expanding,
            QtWidgets.QSizePolicy.Fixed), 1, 4)

        self.tabla = Tabla(self.columnas, horizontalHeader=horizontalHeader,
                           verticalHeader=False, stretch=False)
        self.tabla.setConnected()
        if unit:
            hHeader = []
            for unit, title in zip(self.unit, horizontalHeader):
                hHeader.append("%s, %s" % (title, unit.text()))
            self.tabla.setHorizontalHeaderLabels(hHeader)
            self.tabla.horizontalHeader().sectionClicked.connect(self.editUnit)

        if data:
            self.tabla.setData(data)
            self.tabla.addRow()
        elif t and property:
            self.tabla.setColumn(0, t)
            self.tabla.setColumn(1, property)
        gridLayout.addWidget(self.tabla, 2, 1, 1, 4)

        if DIPPR:
            self.eqDIPPR = eqDIPPR(eq)
            gridLayout.addWidget(self.eqDIPPR, 3, 1, 1, 4)
            self.eqDIPPR.eqDIPPR.valueChanged.connect(self.showTc)

            self.labelTc = QtWidgets.QLabel("Tc: ", self)
            gridLayout.addWidget(self.labelTc, 4, 1)
            self.tc = Entrada_con_unidades(Temperature, value=Tc)
            gridLayout.addWidget(self.tc, 4, 2, 1, 3)
            self.showTc(1)

    def showTc(self, value):
        """Show/hide Tc widget"""
        self.labelTc.setVisible(value in (7, 9))
        self.tc.setVisible(value in (7, 9))

    def open(self):
        """Load data from a test file"""
        fname, ext = QtWidgets.QFileDialog.getOpenFileName(
            self,
            QtWidgets.QApplication.translate("pychemqt", "Open text file"),
            "./")
        if fname:
            try:
                # Numpy raise error if use the fname directly and find a
                # non-latin1 character, inclusive in comment lines
                with open(fname, "rb") as file:
                    data = loadtxt(file)
                self.delete()
                self.tabla.setData(data)
            except ValueError as er:
                # Raise a error msg if the file can load by loadtxt, the user
                # can select any type of file and the input error is possible
                title = QtWidgets.QApplication.translate(
                    "pychemqt", "Failed to load file")
                msg = fname + "\n" + er.args[0]
                QtWidgets.QMessageBox.critical(self, title, msg)

    def save(self):
        """Save currend data of table to a file"""
        fname, ext = QtWidgets.QFileDialog.getSaveFileName(
            self,
            QtWidgets.QApplication.translate("pychemqt", "Save data to file"),
            "./")
        if fname:
            with open(fname, 'w') as file:
                file.write("#"+self.title+"\n")
                file.write("#")
                for i in range(self.tabla.columnCount()):
                    item = self.tabla.horizontalHeaderItem(i)
                    file.write(item.text()+"\t")
                file.write("\n")
                data = self.data
                for fila in range(len(data)):
                    for columna in range(self.tabla.columnCount()):
                        file.write(str(data[fila][columna])+"\t")
                    file.write("\n")

    def delete(self):
        """Clear table"""
        self.tabla.setRowCount(0)
        self.tabla.clearContents()
        self.tabla.addRow()

    @property
    def data(self):
        return self.tabla.getData()

    def column(self, column, magnitud=None, unit="conf"):
        """
        column: column to get
        magnitud: magnitud to get the values
        unit: unit of the values in table"""
        data = self.tabla.getColumn(column)
        if self.unit:
            magnitud = self.unit[column]
            tx = self.tabla.horizontalHeaderItem(column).text().split(", ")[-1]
            unit = magnitud.__units__[magnitud.__text__.index(tx)]

        if magnitud is not None:
            data = [magnitud(x, unit) for x in data]
        return data

    def editUnit(self, col):
        """Show dialog to config input unit"""
        unit = self.unit[col]
        widget = QtWidgets.QComboBox(self.tabla)
        for txt in unit.__text__:
            widget.addItem(txt)
        txt = self.tabla.horizontalHeaderItem(col).text().split(", ")[-1]
        widget.setCurrentText(txt)

        # Define Unit combobox geometry
        size = self.tabla.horizontalHeader().sectionSize(col)
        pos = self.tabla.horizontalHeader().sectionPosition(col)
        h = self.tabla.horizontalHeader().height()
        geometry = QtCore.QRect(pos, 0, size, h)
        widget.setGeometry(geometry)
        widget.currentIndexChanged["int"].connect(
            partial(self.updateHeader, col))
        widget.show()
        widget.showPopup()

    def updateHeader(self, col, index):
        """Change the text in header"""
        widget = self.sender()
        txt = self.tabla.horizontalHeaderItem(col).text()
        newtxt = "%s, %s" % (txt.split(",")[0], widget.currentText())
        self.tabla.setHorizontalHeaderItem(
                col, QtWidgets.QTableWidgetItem(newtxt))
        widget.close()