qtableview_profile.py 14.71 KiB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
import numpy as np
import pandas as pd
from PyQt5.QtGui import QFont

from PyQt5.QtWidgets import QMessageBox
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import QModelIndex, Qt, QAbstractTableModel, QVariant, QCoreApplication

from Model.Geometry.ProfileXYZ import ProfileXYZ

_translate = QCoreApplication.translate


class PandasModelEditable(QAbstractTableModel):
    def __init__(self, profile: ProfileXYZ, table_header=None):
        QAbstractTableModel.__init__(self)

        if table_header is None:
            self.header = ["X (m)", "Y (m)", "Z (m)", _translate("MainWindowProfile", "Nom"),
                           _translate("MainWindowProfile", "Abs en travers (m)")]
        else:
            self.header = table_header

        self.profile = profile

        data = pd.DataFrame({
            self.header[0]: profile.x(),
            self.header[1]: profile.y(),
            self.header[2]: profile.z(),
            self.header[3]: profile.name(),
            self.header[4]: profile.get_station()
        })
        self._data = data

    def rowCount(self, parent=QModelIndex()):
        return self._data.shape[0]

    def columnCount(self, parent=QModelIndex()):
        return self._data.shape[1]

    def data(self, index, role=Qt.DisplayRole):
        value = self._data.iloc[index.row()][index.column()]
        if index.isValid():
            if role == Qt.DisplayRole:
                if index.column() != 4:
                    if isinstance(value, float):
                        return "%.4f" % value
                else:
                    if isinstance(value, float):
                        return "%.3f" % value

                return str(self._data.iloc[index.row(), index.column()])

            if role == Qt.TextAlignmentRole:
                return Qt.AlignHCenter | Qt.AlignVCenter

            # if index.column() == 2:
            #     if role == Qt.ForegroundRole:
            #         if value == min(self._data.iloc[:, index.column()]):
            #             return QtGui.QColor("red")
            #         elif value == max(self._data.iloc[:, index.column()]):
            #             return QtGui.QColor("Blue")

                if role == Qt.ToolTipRole:
                    if value == min(self._data.iloc[:, index.column()]):
                        return _translate("MainWindowProfile", "La cote du fond", "Z minimale")
                    elif value == max(self._data.iloc[:, index.column()]):
                        return _translate("MainWindowProfile", "La cote maximale", "Z maximale")

            if index.column() == 3:
                if value.strip().upper() in ["RG", "RD"]:
                    if role == Qt.FontRole:
                        font = QFont()
                        font.setBold(True)
                        return font

                    if role == Qt.ForegroundRole:
                        return QtGui.QColor("darkRed")

                    if role == Qt.ToolTipRole:
                        if value.strip().upper() == "RG":
                            return _translate("MainWindowProfile", "Rive gauche")
                        else:
                            return _translate("MainWindowProfile", "Rive droite")

            if index.column() == 4:
                if role == Qt.FontRole:
                    font = QFont()
                    font.setBold(True)
                    return font

                # if role == Qt.BackgroundRole:
                #     return QtGui.QColor("#ededee")

        return QVariant()

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.header[section]

        if role == Qt.ToolTipRole and section == 4:
            return _translate(
                "MainWindowProfile",
                "Abscisse en travers calculée en projétant les points"
                " \nsur le plan défini par les deux points nommés extrêmes "
            )

        if orientation == Qt.Vertical and role == Qt.DisplayRole:
            return self._data.index[section] + 1

        return None

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.EditRole:
            try:
                if index.column() == 3:
                    self._data.iat[index.row(), index.column()] = str(value)
                elif index.column() == 0:
                    self._data.iat[index.row(), index.column()] = float(value)
                elif index.column() == 1:
                    self._data.iat[index.row(), index.column()] = float(value)
                elif index.column() == 2:
                    self._data.iat[index.row(), index.column()] = float(value)

                self._data.iloc[:, 4] = projection_pointXYZ.update_station(
                    self.header,
                    self._data.values.tolist()
                )
                self.dataChanged.emit(index, index)
            except:
                print('TODO')
                self.QMessageBoxCritical(value)

            return True

        self.dataChanged.emit(index, index)
        self.layoutChanged.emit()

        return False

    @staticmethod
    def QMessageBoxCritical(value):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setText("{} : Valeur saisie incorrecte ".format(value))
        msg.setInformativeText("Seules les valeurs numériques sont autorisées.")
        msg.setWindowTitle("Warning ")
        msg.setStyleSheet("QLabel{min-width:150 px; font-size: 13px;} QPushButton{ width:20px; font-size: 12px};"
                          "background-color: Ligthgray ; color : gray;font-size: 8pt; color: #888a80;")
        msg.exec_()

    def index(self, row, column, parent=QModelIndex()):
        if not self.hasIndex(row, column, parent):
            return QModelIndex()
        return self.createIndex(row, column, QModelIndex())

    def flags(self, index):
        return Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled

    # @QtCore.pyqtSlot()
    def insertRows(self, row, count, parent=QModelIndex()):
        self.beginInsertRows(parent, row, row + count - 1)
        indexes = [str(self.rowCount() + i) for i in range(count)]
        left = self._data[0:row]
        mid = pd.DataFrame(index=indexes, columns=self._data.columns)
        right = self._data[row + count - 1:self.rowCount()]

        self._data = pd.concat([left, mid, right])

        for i in [3]:
            self._data.iloc[:, i].replace(np.nan, '', inplace=True)

        self._data.reset_index(drop=True, inplace=True)

        try:
            self._data.iloc[:, 4] = projection_pointXYZ.update_station(
                self.header,
                self._data.values.tolist()
            )
        except:
            print("TODO")

        self.endInsertRows()
        self.layoutChanged.emit()

    # @QtCore.pyqtSlot()
    def removeRows(self, row, count, parent=QModelIndex()):
        self.beginRemoveRows(parent, row, row + count + 1)
        self._data.drop(self._data.index[row], inplace=True)
        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )
        self.endRemoveRows()
        self.layoutChanged.emit()

    def remove_rows1(self, row, count, parent=QModelIndex()):
        self.beginRemoveRows(parent, row, row + count - 1)
        left = self._data.iloc[0:row]
        right = self._data.iloc[row + count:self.rowCount()]

        self._data = pd.concat([left, right], axis=0, ignore_index=True)
        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )
        self.endRemoveRows()
        self.layoutChanged.emit()

    def remove_rows(self, list_row_selected, parent=QModelIndex()):
        self.beginRemoveRows(parent, list_row_selected[0], list_row_selected[-1])

        try:
            self._data.drop(self._data.index[list_row_selected], inplace=True)
            self._data.reset_index(drop=True, inplace=True)
        except:
            print('TODO')
        try:
            self._data.iloc[:, 4] = projection_pointXYZ.update_station(
                self.header,
                self._data.values.tolist()
            )
        except:
            print("TODO")

        self.endRemoveRows()
        self.layoutChanged.emit()

    def sort(self, column, order=Qt.AscendingOrder):
        self.layoutAboutToBeChanged.emit()
        colname = self._data.columns.tolist()[column]
        self._data.sort_values(colname, ascending=order == Qt.AscendingOrder, inplace=True)
        self._data.reset_index(inplace=True, drop=True)

        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )
        self.layoutChanged.emit()

    def moveRowDown(self, row_to_move, parent=QModelIndex()):
        target = row_to_move + 2
        self.beginMoveRows(parent, row_to_move, row_to_move, parent, target)
        block_before_row = self._data.iloc[0:row_to_move]
        selected_row = self._data.iloc[row_to_move:row_to_move + 1]
        after_selcted_row = self._data.iloc[row_to_move + 1:row_to_move + 2]
        block_after_row = self._data.iloc[row_to_move + 2:self.rowCount()]

        self._data = pd.concat([block_before_row, after_selcted_row, selected_row, block_after_row], axis=0)
        self._data.reset_index(inplace=True, drop=True)

        self.endMoveRows()
        self.layoutChanged.emit()

    def moveRowUp(self, row_to_move, parent=QModelIndex()):
        target = row_to_move + 1
        self.beginMoveRows(parent, row_to_move - 1, row_to_move - 1, parent, target)
        block_before_row = self._data.iloc[0:row_to_move - 1]
        before_selected_row = self._data.iloc[row_to_move - 1:row_to_move]
        selected_row = self._data.iloc[row_to_move:row_to_move + 1]
        block_after_row = self._data.iloc[row_to_move + 1:self.rowCount()]

        self._data = pd.concat([block_before_row, selected_row, before_selected_row, block_after_row], axis=0)
        self._data.reset_index(inplace=True, drop=True)

        self.endMoveRows()
        self.layoutChanged.emit()

    def copyTable(self, start_selection, end_selection):
        end_selection = self.rowCount()

        self._data.loc[start_selection:end_selection]\
                  .to_clipboard(header=None, index=False, excel=True, sep='\t')

    def insert_df_to_idx(self, idx, df, df_insert):
        """
        Args:
            idx: is the index position in df where you want to insert new dataframe (df_insert)
            df: dataframe
            df_insert: dataframe to insert
        Returns:
            The dataframe df with df_insert inserted at index idx.
        """
        return df.iloc[:idx, ].append(df_insert).append(df.iloc[idx:, ]).reset_index(drop=True)

    def pasteTable(self, insertion_index):
        self.layoutAboutToBeChanged.emit()
        df = pd.read_clipboard(header=None, skip_blank_lines=True,
                               sep="\t", names=self.header)
        self._data = self.insert_df_to_idx(insertion_index, self._data, df)

        for i in [3]:
            self._data.iloc[:, i].replace(np.nan, '', inplace=True)

        self.layoutChanged.emit()
        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )

    @property
    def model_data(self):
        return self._data

    @model_data.setter
    def model_data(self, new_data):
        self._data = new_data
        self.layoutChanged.emit()

    @property
    def x(self):
        return self._data.iloc[:, 0].tolist()

    @property
    def y(self):
        return self._data.iloc[:, 1].tolist()

    @property
    def z(self):
        return self._data.iloc[:, 2].tolist()

    @property
    def name(self):
        return self._data.iloc[:, 3].tolist()

    def get_data(self):
        return self._data

    @property
    def station(self):
        return self._data.iloc[:, 4].tolist()

    def remove_duplicates_names(self):
        counter_list = []
        list_deleted_names = []
        ind_ind = []

        for ind, name_point in enumerate(self.name):
            if name_point not in counter_list:
                counter_list.append(name_point)
            elif len(name_point.strip()) > 0 and name_point in counter_list:
                ind_ind.append(ind)

                if name_point not in list_deleted_names:
                    list_deleted_names.append(name_point)

        for ind in ind_ind:
            self._data.iat[ind, 3] = ""

    def data_contains_nan(self) -> bool:
        """
        Returns:
            Returns True if the QTableView() contains np.nan
        """
        return self._data.isnull().values.any()

    def delete_empty_rows(self):
        self.layoutAboutToBeChanged.emit()

        self._data.dropna(inplace=True)
        self._data.reset_index(drop=True, inplace=True)

        self.layoutChanged.emit()

    def valide_all_changes(self):
        self.profile.x = self._data.iloc[:, 0]
        self.profile.y = self._data.iloc[:, 1]
        self.profile.z = self._data.iloc[:, 2]
        self.profile.ld = self._data.iloc[:, 3]


class Delegate(QtWidgets.QStyledItemDelegate):
    def __init__(self, parent=None, setModelDataEvent=None):
        super(Delegate, self).__init__(parent)
        self.setModelDataEvent = setModelDataEvent

    def createEditor(self, parent, option, index):
        """
        Args:
            parent:
            option:
            index:
        Returns:
            Le widget (éditeur) pour éditer l'item se trouvant à l'index index.
        """
        index.model().data(index, Qt.DisplayRole)
        return QtWidgets.QLineEdit(parent)

    def setEditorData(self, editor, index):
        """
        Args:
            editor: l'éditeur
            index: l'index
        Returns: permet de transmettre à l'éditeur editor les données à afficher à partir du modèle se trouvant
                à l'index index.
        """
        value = index.model().data(index, Qt.DisplayRole)
        editor.setText(str(value))

    def setModelData(self, editor, model, index):
        """
        Args:
            editor: l'éditeur
            model: le modèle
            index: l'index
        Returns: permet de récupérer les données de l'éditeur et de les stocker à l'intérieur du modèle, à l'index
                identifié par le paramètre index
        """
        model.setData(index, editor.text())

        if not self.setModelDataEvent is None:
            self.setModelDataEvent()

    def updateEditorGeometry(self, editor, option, index):
        """
        Args:
            editor: l'éditeur
            option:
            index: l'index
        Returns: Permet de redimensionner l'éditeur à la bonne taille lorsque la taille de la vue change
        """
        editor.setGeometry(option.rect)