Exemplo n.º 1
0
    def on_copy(self):
        select_group_dialog = QDialog(self)
        select_group_dialog.resize(300, 400)
        select_group_dialog.setWindowTitle(self.tr("Choose source group"))
        layout = QVBoxLayout(select_group_dialog)
        select_group_dialog.setLayout(layout)

        groups_list_view = QTableView(self)
        layout.addWidget(groups_list_view)
        groups_list_view.setModel(self.ds_model)
        groups_list_view.setColumnHidden(DSManagerModel.COLUMN_VISIBILITY,
                                         True)
        groups_list_view.setSelectionMode(QTableView.NoSelection)
        groups_list_view.setAlternatingRowColors(True)
        groups_list_view.setShowGrid(False)
        if hasattr(groups_list_view.horizontalHeader(), "setResizeMode"):
            # Qt4
            groups_list_view.horizontalHeader().setResizeMode(
                DSManagerModel.COLUMN_GROUP_DS, QHeaderView.Stretch)
            groups_list_view.verticalHeader().setResizeMode(
                QHeaderView.ResizeToContents)
        else:
            # Qt5
            groups_list_view.horizontalHeader().setSectionResizeMode(
                DSManagerModel.COLUMN_GROUP_DS, QHeaderView.Stretch)
            groups_list_view.verticalHeader().setSectionResizeMode(
                QHeaderView.ResizeToContents)

        groups_list_view.verticalHeader().hide()
        groups_list_view.clicked.connect(
            lambda index: select_group_dialog.accept() \
                if self.ds_model.isGroup(index) and \
                    index.column() == DSManagerModel.COLUMN_GROUP_DS \
                else None
        )

        if select_group_dialog.exec_() == QDialog.Accepted:
            group_info = self.ds_model.data(groups_list_view.currentIndex(),
                                            Qt.UserRole)
            group_info.id += "_copy"
            edit_dialog = GroupEditDialog()
            edit_dialog.setWindowTitle(self.tr('Create group from existing'))
            edit_dialog.fill_group_info(group_info)
            if edit_dialog.exec_() == QDialog.Accepted:
                self.feel_list()
                self.ds_model.resetModel()
Exemplo n.º 2
0
 def __init__(self, parent=None):
     super(testWidget, self).__init__(parent)
     # this layout_box can be used if you need more widgets
     # I used just one named WebsitesWidget
     layout_box = QVBoxLayout(self)
     #
     my_view = QTableView()
     # put view in layout_box area
     layout_box.addWidget(my_view)
     # create a table model
     """
     my_model = SqlQueryModel()
     q = QSqlQuery(query)
     my_model.setQuery(q)
     my_model.setFilter("SurveyID = 1 AND SectionID = 31")
     my_model.select()
     my_view.setModel(my_model)
     """
     my_model = QSqlRelationalTableModel(self)
     my_model.setTable("VRMs")
     #q = QSqlQuery()
     #result = q.prepare("SELECT PositionID, VRM, VehicleTypeID, RestrictionTypeID, PermitType, Notes FROM VRMs")
     #if result == False:
     #    print ('Prepare: {}'.format(q.lastError().text()))
     #my_model.setQuery(q)
     my_model.setFilter("SurveyID = 38 AND SectionID = 31")
     my_model.setSort(int(my_model.fieldIndex("PositionID")),
                      Qt.AscendingOrder)
     my_model.setRelation(
         int(my_model.fieldIndex("VehicleTypeID")),
         QSqlRelation('VehicleTypes', 'Code', 'Description'))
     rel = my_model.relation(int(my_model.fieldIndex("VehicleTypeID")))
     if not rel.isValid():
         print('Relation not valid ...')
     result = my_model.select()
     if result == False:
         print('Select: {}'.format(q.lastError().text()))
     #show the view with model
     my_view.setModel(my_model)
     my_view.setColumnHidden(my_model.fieldIndex('fid'), True)
     my_view.setColumnHidden(my_model.fieldIndex('ID'), True)
     my_view.setColumnHidden(my_model.fieldIndex('SurveyID'), True)
     my_view.setColumnHidden(my_model.fieldIndex('SectionID'), True)
     my_view.setColumnHidden(my_model.fieldIndex('GeometryID'), True)
     my_view.setItemDelegate(QSqlRelationalDelegate(my_view))
Exemplo n.º 3
0
    def on_copy(self):
        select_group_dialog = QDialog(self)
        select_group_dialog.resize(300, 400)
        select_group_dialog.setWindowTitle(self.tr("Choose source group"))
        layout = QVBoxLayout(select_group_dialog)
        select_group_dialog.setLayout(layout)

        groups_list_view = QTableView(self)
        layout.addWidget(groups_list_view)
        groups_list_view.setModel(self.ds_model)
        groups_list_view.setColumnHidden(DSManagerModel.COLUMN_VISIBILITY, True)
        groups_list_view.setSelectionMode(QTableView.NoSelection)
        groups_list_view.setAlternatingRowColors(True)
        groups_list_view.setShowGrid(False)
        if hasattr(groups_list_view.horizontalHeader(), "setResizeMode"):
            # Qt4
            groups_list_view.horizontalHeader().setResizeMode(DSManagerModel.COLUMN_GROUP_DS, QHeaderView.Stretch)
            groups_list_view.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
        else:
            # Qt5
            groups_list_view.horizontalHeader().setSectionResizeMode(DSManagerModel.COLUMN_GROUP_DS, QHeaderView.Stretch)
            groups_list_view.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

        groups_list_view.verticalHeader().hide()
        groups_list_view.clicked.connect(
            lambda index: select_group_dialog.accept() \
                if self.ds_model.isGroup(index) and \
                    index.column() == DSManagerModel.COLUMN_GROUP_DS \
                else None
        )

        if select_group_dialog.exec_() == QDialog.Accepted:
            group_info = self.ds_model.data(groups_list_view.currentIndex(), Qt.UserRole)
            group_info.id += "_copy"
            edit_dialog = GroupEditDialog()
            edit_dialog.setWindowTitle(self.tr('Create group from existing'))
            edit_dialog.fill_group_info(group_info)
            if edit_dialog.exec_() == QDialog.Accepted:
                self.feel_list()
                self.ds_model.resetModel()
Exemplo n.º 4
0
class FreezeTableWidget(QTableView):

    def __init__(
            self, table_data, headers, parent=None, *args
    ):
        """
        Creates two QTableViews one of which is a frozen table while the
        other one can scroll behind it.
        :param table_data: The data that goes into the tables
        :type table_data: List
        :param headers: The header data of the tables.
        :type headers: List
        :param parent: The parent of the QTableView
        :type parent: QWidget
        :param args:
        :type args:
        """
        QTableView.__init__(self, parent)
        # set the table model
        self.table_model = BaseSTDMTableModel(
            table_data, headers, parent
        )
        # set the proxy model
        proxy_model = QSortFilterProxyModel(self)
        proxy_model.setSourceModel(self.table_model)
        # Assign a data model for TableView
        self.setModel(self.table_model)
        # frozen_table_view - first column
        self.frozen_table_view = QTableView(self)
        # Set the model for the widget, fixed column
        self.frozen_table_view.setModel(self.table_model)
        # Hide row headers
        self.frozen_table_view.verticalHeader().hide()
        # Widget does not accept focus
        self.frozen_table_view.setFocusPolicy(
            Qt.StrongFocus | Qt.TabFocus | Qt.ClickFocus
        )
        # The user can not resize columns
        self.frozen_table_view.horizontalHeader(). \
            setSectionResizeMode(QHeaderView.Fixed)
        self.frozen_table_view.setObjectName('frozen_table')
        self.setSelectionMode(QAbstractItemView.NoSelection)
        # Remove the scroll bar
        self.frozen_table_view.setHorizontalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff
        )
        self.frozen_table_view.setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff
        )
        # Puts more widgets to the foreground
        self.viewport().stackUnder(self.frozen_table_view)
        # # Log in to edit mode - even with one click
        # Set the properties of the column headings
        hh = self.horizontalHeader()
        # Text alignment centered
        hh.setDefaultAlignment(Qt.AlignCenter)

        self.set_column_width()
        # Set properties header lines
        vh = self.verticalHeader()
        vh.setDefaultSectionSize(25)  # height lines
        # text alignment centered
        vh.setDefaultAlignment(Qt.AlignCenter)
        vh.setVisible(True)
        # Height of rows - as in the main widget
        self.frozen_table_view.verticalHeader(). \
            setDefaultSectionSize(
            vh.defaultSectionSize()
        )
        # Show frozen table view
        self.frozen_table_view.show()
        # Set the size of him like the main

        self.setHorizontalScrollMode(
            QAbstractItemView.ScrollPerPixel
        )
        self.setVerticalScrollMode(
            QAbstractItemView.ScrollPerPixel
        )
        self.frozen_table_view.setVerticalScrollMode(
            QAbstractItemView.ScrollPerPixel
        )
        ## select the first column (STR Type)
        self.frozen_table_view.selectColumn(0)

        self.frozen_table_view.setEditTriggers(
            QAbstractItemView.AllEditTriggers
        )
        self.set_size()
        self.signals()

    def set_size(self):
        """
        Sets the size and size policy of the tables.
        :return:
        :rtype:
        """
        size_policy = QSizePolicy(
            QSizePolicy.Fixed, QSizePolicy.Fixed
        )
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.sizePolicy().hasHeightForWidth()
        )
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QSize(55, 75))
        self.setMaximumSize(QSize(5550, 5555))
        self.SelectionMode(
            QAbstractItemView.SelectColumns
        )
        # set column width to fit contents
        self.frozen_table_view.resizeColumnsToContents()
        # set row height
        self.frozen_table_view.resizeRowsToContents()

    def signals(self):
        """
        Connects signals of the tables.
        """
        # Connect the headers and scrollbars of
        # both tableviews together
        self.horizontalHeader().sectionResized.connect(
            self.update_section_width
        )
        self.verticalHeader().sectionResized.connect(
            self.update_section_height
        )
        self.frozen_table_view.verticalScrollBar().valueChanged.connect(
            self.verticalScrollBar().setValue
        )
        self.verticalScrollBar().valueChanged.connect(
            self.frozen_table_view.verticalScrollBar().setValue
        )

    def set_column_width(self):
        """
        Sets the column width of the frozen QTableView.
        """
        # Set the width of columns
        columns_count = self.table_model.columnCount(self)
        for col in range(columns_count):
            if col == 0:
                # Set the size
                self.horizontalHeader().resizeSection(
                    col, 60
                )
                # Fix width
                self.horizontalHeader().setSectionResizeMode(
                    col, QHeaderView.Fixed
                )
                # Width of a fixed column - as in the main widget
                self.frozen_table_view.setColumnWidth(
                    col, self.columnWidth(col)
                )
            elif col == 1:
                self.horizontalHeader().resizeSection(
                    col, 150
                )
                self.horizontalHeader().setSectionResizeMode(
                    col, QHeaderView.Fixed
                )
                self.frozen_table_view.setColumnWidth(
                    col, self.columnWidth(col)
                )
            else:
                self.horizontalHeader().resizeSection(
                    col, 150
                )
                # Hide unnecessary columns in the
                # widget fixed columns
                self.frozen_table_view.setColumnHidden(
                    col, True
                )

    def add_widgets(self, spatial_unit, insert_row):
        """
        Adds widget into the frozen table.
        :param str_type_id: The STR type id of the tenure type combobox
        :type str_type_id: Integer
        :param insert_row: The row number the widgets to be added.
        :type insert_row: Integer
        """
        delegate = STRTypeDelegate(spatial_unit)
        # Set delegate to add combobox under
        # social tenure type column
        self.frozen_table_view.setItemDelegate(
            delegate
        )
        self.frozen_table_view.setItemDelegateForColumn(
            0, delegate
        )
        index = self.frozen_table_view.model().index(
            insert_row, 0, QModelIndex()
        )
        self.frozen_table_view.model().setData(
            index, '', Qt.EditRole
        )

        self.frozen_table_view.openPersistentEditor(
            self.frozen_table_view.model().index(insert_row, 0)
        )
        self.frozen_table_view.openPersistentEditor(
            self.frozen_table_view.model().index(insert_row, 1)
        )

    def update_section_width(
            self, logicalIndex, oldSize, newSize
    ):
        """
        Updates frozen table column width and geometry.
        :param logicalIndex: The section's logical number
        :type logicalIndex: Integer
        :param oldSize: The old size of the section
        :type oldSize: Integer
        :param newSize: The new size of the section
        :type newSize: Integer
        """
        if logicalIndex == 0 or logicalIndex == 1:
            self.frozen_table_view.setColumnWidth(
                logicalIndex, newSize
            )
            self.update_frozen_table_geometry()

    def update_section_height(
            self, logicalIndex, oldSize, newSize
    ):
        """
        Updates frozen table column height.
        :param logicalIndex: The section's logical number
        :type logicalIndex: Integer
        :param oldSize: The old size of the section
        :type oldSize: Integer
        :param newSize: The new size of the section
        :type newSize: Integer
        """
        self.frozen_table_view.setRowHeight(
            logicalIndex, newSize
        )

    def resizeEvent(self, event):
        """
        Handles the resize event of the frozen table view.
        It updates the frozen table view geometry on resize of table.
        :param event: The event
        :type event: QEvent
        """
        QTableView.resizeEvent(self, event)
        try:
            self.update_frozen_table_geometry()
        except DummyException as log:
            LOGGER.debug(str(log))

    def scrollTo(self, index, hint):
        """
        Scrolls the view if necessary to ensure that the item at index is
        visible. The view will try to position the item according to the
        given hint.
        :param index: The scroll index
        :type index: QModelIndex
        :param hint: The scroll hint
        :type hint: Integer
        """
        if index.column() > 1:
            QTableView.scrollTo(self, index, hint)

    def update_frozen_table_geometry(self):
        """
        Updates the frozen table view geometry.
        """
        if self.verticalHeader().isVisible():
            self.frozen_table_view.setGeometry(
                self.verticalHeader().width() +
                self.frameWidth(),
                self.frameWidth(),
                self.columnWidth(0) + self.columnWidth(1),
                self.viewport().height() +
                self.horizontalHeader().height()
            )
        else:
            self.frozen_table_view.setGeometry(
                self.frameWidth(),
                self.frameWidth(),
                self.columnWidth(0) + self.columnWidth(1),
                self.viewport().height() +
                self.horizontalHeader().height()
            )

    def move_cursor(self, cursor_action, modifiers):
        """
        Override function for correct left to scroll the keyboard.
        Returns a QModelIndex object pointing to the next object in the
        table view, based on the given cursorAction and keyboard modifiers
        specified by modifiers.
        :param cursor_action: The cursor action
        :type cursor_action: Integer
        :param modifiers: Qt.KeyboardModifier value.
        :type modifiers: Object
        :return: The current cursor position.
        :rtype: QModelIndex
        """
        current = QTableView.move_cursor(
            self, cursor_action, modifiers
        )
        if cursor_action == self.MoveLeft and current.column() > 1 and \
                self.visualRect(current).topLeft().x() < \
                (self.frozen_table_view.columnWidth(0) +
                 self.frozen_table_view.columnWidth(1)):
            new_value = self.horizontalScrollBar().value() + \
                        self.visualRect(current).topLeft().x() - \
                        (self.frozen_table_view.columnWidth(0) +
                         self.frozen_table_view.columnWidth(1))
            self.horizontalScrollBar().setValue(new_value)
        return current
Exemplo n.º 5
0
class ForeignKeyMapper(QWidget):
    """
    Widget for selecting database records through an entity browser or
    using an ExpressionBuilder for filtering records.
    """
    # Custom signals
    beforeEntityAdded = pyqtSignal("PyQt_PyObject")
    afterEntityAdded = pyqtSignal("PyQt_PyObject", int)
    entityRemoved = pyqtSignal("PyQt_PyObject")
    deletedRows = pyqtSignal(list)

    def __init__(self,
                 entity,
                 parent=None,
                 notification_bar=None,
                 enable_list=True,
                 can_filter=False,
                 plugin=None):

        QWidget.__init__(self, parent)
        self.current_profile = current_profile()

        self._tbFKEntity = QTableView(self)
        self._tbFKEntity.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self._tbFKEntity.setAlternatingRowColors(True)
        self._tbFKEntity.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.plugin = plugin
        self._add_entity_btn = QToolButton(self)
        self._add_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Add"))
        self._add_entity_btn.setIcon(GuiUtils.get_icon("add.png"))
        self._add_entity_btn.clicked.connect(self.onAddEntity)

        self._edit_entity_btn = QToolButton(self)
        self._edit_entity_btn.setVisible(False)
        self._edit_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Edit"))
        self._edit_entity_btn.setIcon(GuiUtils.get_icon("edit.png"))

        self._filter_entity_btn = QToolButton(self)
        self._filter_entity_btn.setVisible(False)
        self._filter_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Select by expression"))
        self._filter_entity_btn.setIcon(GuiUtils.get_icon("filter.png"))
        self._filter_entity_btn.clicked.connect(self.onFilterEntity)

        self._delete_entity_btn = QToolButton(self)
        self._delete_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Remove"))
        self._delete_entity_btn.setIcon(GuiUtils.get_icon("remove.png"))
        self._delete_entity_btn.clicked.connect(self.onRemoveEntity)

        layout = QVBoxLayout(self)
        layout.setSpacing(4)
        layout.setMargin(5)

        self.grid_layout = QGridLayout()
        self.grid_layout.setHorizontalSpacing(5)
        self.grid_layout.addWidget(self._add_entity_btn, 0, 0, 1, 1)
        self.grid_layout.addWidget(self._filter_entity_btn, 0, 1, 1, 1)
        self.grid_layout.addWidget(self._edit_entity_btn, 0, 2, 1, 1)
        self.grid_layout.addWidget(self._delete_entity_btn, 0, 3, 1, 1)
        self.grid_layout.setColumnStretch(4, 5)

        layout.addLayout(self.grid_layout)
        layout.addWidget(self._tbFKEntity)
        self.social_tenure = self.current_profile.social_tenure

        self._tableModel = None
        self._notifBar = notification_bar
        self._headers = []
        self._entity_attrs = []
        self._cell_formatters = {}
        self._searchable_columns = OrderedDict()
        self._supportsLists = enable_list
        self._deleteOnRemove = False
        self._uniqueValueColIndices = OrderedDict()
        self.global_id = None
        self._deferred_objects = {}
        self._use_expression_builder = can_filter

        if self._use_expression_builder:
            self._filter_entity_btn.setVisible(True)
            self._edit_entity_btn.setVisible(False)
        self.set_entity(entity)

    def set_entity(self, entity):
        """
        Sets new entity and updates the ForeignKeyMapper with a new
        :param entity: The entity of the ForeignKeyMapper
        :type entity:Object
        """
        from stdm.ui.entity_browser import EntityBrowser

        self._entity = entity

        self._dbmodel = entity_model(entity)
        self._init_fk_columns()
        self._entitySelector = EntityBrowser(self._entity,
                                             parent=self,
                                             state=SELECT,
                                             plugin=self.plugin)

        # Connect signals
        self._entitySelector.recordSelected.connect(
            self._onRecordSelectedEntityBrowser)

    def _init_fk_columns(self):
        """
        Asserts if the entity columns actually do exist in the database. The
        method also initializes the table headers, entity column and cell
        formatters.
        """
        self._headers[:] = []
        self._entity_attrs[:] = []
        if self._dbmodel is None:
            msg = QApplication.translate(
                'ForeignKeyMapper', 'The data model for '
                'the entity could '
                'not be loaded, '
                'please contact '
                'your database '
                'administrator.')
            QMessageBox.critical(
                self, QApplication.translate('EntityBrowser',
                                             'Entity Browser'), msg)

            return

        table_name = self._entity.name
        columns = table_column_names(table_name)
        missing_columns = []

        header_idx = 0

        # Iterate entity column and assert if they exist
        for c in self._entity.columns.values():
            # Do not include virtual columns in list of missing columns
            if not c.name in columns and not isinstance(c, VirtualColumn):
                missing_columns.append(c.name)

            else:
                header = c.header()
                self._headers.append(header)
                '''
                If it is a virtual column then use column name as the header
                but fully qualified column name (created by SQLAlchemy
                relationship) as the entity attribute name.
                '''
                col_name = c.name

                if isinstance(c, MultipleSelectColumn):
                    col_name = c.model_attribute_name

                self._entity_attrs.append(col_name)

                # Get widget factory so that we can use the value formatter
                w_factory = ColumnWidgetRegistry.factory(c.TYPE_INFO)
                if not w_factory is None:
                    try:
                        formatter = w_factory(c)
                        self._cell_formatters[col_name] = formatter
                    except WidgetException as we:
                        msg = QApplication.translate(
                            'ForeignKeyMapper', 'Error in creating column:')
                        msg = '{0} {1}:{2}\n{3}'.format(
                            msg, self._entity.name, c.name, str(we))
                        QMessageBox.critical(
                            self,
                            QApplication.translate('ForeignKeyMapper',
                                                   'Widget Creation Error'),
                            msg)

                # Set searchable columns
                if c.searchable:
                    self._searchable_columns[header] = {
                        'name': c.name,
                        'header_index': header_idx
                    }

                header_idx += 1

        if len(missing_columns) > 0:
            msg = QApplication.translate(
                'ForeignKeyMapper',
                'The following columns have been defined in the '
                'configuration but are missing in corresponding '
                'database table, please re-run the configuration wizard '
                'to create them.\n{0}'.format('\n'.join(missing_columns)))

            QMessageBox.warning(
                self,
                QApplication.translate('ForeignKeyMapper', 'Entity Browser'),
                msg)

        self._tableModel = BaseSTDMTableModel([], self._headers, self)
        self._tbFKEntity.setModel(self._tableModel)
        # First (id) column will always be hidden
        self._tbFKEntity.hideColumn(0)

        self._tbFKEntity.horizontalHeader().setSectionResizeMode(
            QHeaderView.Interactive)
        self._tbFKEntity.horizontalHeader().setStretchLastSection(True)

        self._tbFKEntity.verticalHeader().setVisible(True)

    def databaseModel(self):
        '''
        Returns the database model that represents the foreign key entity.
        '''
        return self._dbmodel

    def setDatabaseModel(self, model):
        '''
        Set the database model that represents the foreign key entity.
        Model has to be a callable.
        '''
        self._dbmodel = model

    def cellFormatters(self):
        """
        Returns a dictionary of cell formatters used by the foreign key mapper.
        """
        return self._cell_formatters

    def cell_formatter(self, column):
        """
        :param column: Column name:
        :type column: str
        :return: Returns the corresponding formatter object based on the
        column name. None will be returned if there is no corresponding
        object.
        :rtype: object
        """
        return self._cell_formatters.get(column, None)

    def entitySelector(self):
        '''
        Returns the dialog for selecting the entity objects.
        '''
        return self._entitySelector

    def supportList(self):
        '''
        Returns whether the mapper supports only one item or multiple entities.
        Default is 'True'.
        '''
        return self._supportsLists

    def setSupportsList(self, supportsList):
        '''
        Sets whether the mapper supports only one item or multiple entities i.e.
        one-to-one (False) and one-to-many mapping (True).
        '''
        self._supportsLists = supportsList

    def setNotificationBar(self, notificationBar):
        '''
        Set the notification bar for displaying user messages.
        '''
        self._notifBar = notificationBar

    def viewModel(self):
        '''
        Return the view model used by the table view.
        '''
        return self._tableModel

    def set_expression_builder(self, state):
        """
        Set the mapper to use QGIS expression builder as the entity selector.
        """
        self._use_expression_builder = state

    def expression_builder_enabled(self):
        """
        Returns whether the mapper has been configured to use the expression builder
        """
        return self._use_expression_builder

    def deleteOnRemove(self):
        '''
        Returns the state whether a record should be deleted from the database when it
        is removed from the list.
        '''
        return self._deleteOnRemove

    def setDeleteonRemove(self, delete):
        '''
        Set whether whether a record should be deleted from the database when it
        is removed from the list.
        '''
        self._deleteOnRemove = delete

    def addUniqueColumnName(self, colName, replace=True):
        '''
        Set the name of the column whose values are to be unique.
        If 'replace' is True then the existing row will be replaced
        with one with the new value; else, the new row will not be added to the list.
        '''
        headers = list(self._dbmodel.displayMapping().values())
        colIndex = getIndex(headers, colName)

        if colIndex != -1:
            self.addUniqueColumnIndex(colIndex, replace)

    def addUniqueColumnIndex(self, colIndex, replace=True):
        '''
        Set the index of the column whose values are to be unique. The column indices are
        zero-based.
        If 'replace' is True then the existing row will be replaced with the
        new value; else, the new row will not be added to the list.
        For multiple replace rules defined, then the first one added to the collection is the
        one that will be applied.
        '''
        self._uniqueValueColIndices[colIndex] = replace

    def onFilterEntity(self):
        """
        Slot raised to load the expression builder dialog.
        """
        vl, msg = self.vector_layer()

        if vl is None:
            msg = msg + "\n" + QApplication.translate(
                "ForeignKeyMapper",
                "The expression builder cannot be used at this moment.")
            QMessageBox.critical(
                self,
                QApplication.translate("ForeignKeyMapper",
                                       "Expression Builder"), msg)

            return

        context = self._entity.short_name

        filter_dlg = ForeignKeyMapperExpressionDialog(vl,
                                                      self,
                                                      context=context)
        filter_dlg.setWindowTitle(
            QApplication.translate("ForeignKeyMapper", "Filter By Expression"))
        filter_dlg.recordSelected[int].connect(
            self._onRecordSelectedEntityBrowser)

        res = filter_dlg.exec_()

    def _removeRow(self, rowNumber):
        '''
        Remove the row at the given index.
        '''
        self._tableModel.removeRows(rowNumber, 1)

    def onRemoveEntity(self):
        '''
        Slot raised on clicking to remove the selected entity.
        '''
        selectedRowIndices = self._tbFKEntity.selectionModel().selectedRows(0)

        deleted_rows = []
        if len(selectedRowIndices) == 0:
            msg = QApplication.translate(
                "ForeignKeyMapper", "Please select the record to be removed.")
            self._notifBar.clear()
            self._notifBar.insertWarningNotification(msg)
            return

        for selectedRowIndex in selectedRowIndices:
            # Delete record from database if flag has been set to True
            recId = selectedRowIndex.data()

            dbHandler = self._dbmodel()
            delRec = dbHandler.queryObject().filter(
                self._dbmodel.id == recId).first()

            if not delRec is None:
                self.entityRemoved.emit(delRec)

                if self._deleteOnRemove:
                    delRec.delete()

            self._removeRow(selectedRowIndex.row())

            deleted_rows.append(selectedRowIndex.row())

        self.deletedRows.emit(deleted_rows)

    def _recordIds(self):
        '''
        Returns the primary keys of the records in the table.
        '''
        recordIds = []

        if self._tableModel:
            rowCount = self._tableModel.rowCount()

            for r in range(rowCount):
                # Get ID value
                modelIndex = self._tableModel.index(r, 0)
                modelId = modelIndex.data()
                recordIds.append(modelId)

        return recordIds

    def entities(self):
        '''
        Returns the model instance(s) depending on the configuration specified by the user.
        '''
        recIds = self._recordIds()

        modelInstances = self._modelInstanceFromIds(recIds)

        if len(modelInstances) == 0:
            if self._supportsLists:
                return []

            else:
                return None

        else:
            if self._supportsLists:
                return modelInstances

            else:
                return modelInstances[0]

    def setEntities(self, entities):
        '''
        Insert entities into the table.
        '''
        if isinstance(entities, list):
            for entity in entities:
                self._insertModelToView(entity)

        else:
            self._insertModelToView(entities)

    def searchModel(self, columnIndex, columnValue):
        '''
        Searches for 'columnValue' in the column whose index is specified by 'columnIndex' in all
        rows contained in the model.
        '''
        if isinstance(columnValue, QVariant):
            columnValue = str(columnValue.toString())

        if not isinstance(columnValue, str):
            columnValue = str(columnValue)

        columnValue = columnValue.strip()

        proxy = QSortFilterProxyModel(self)
        proxy.setSourceModel(self._tableModel)
        proxy.setFilterKeyColumn(columnIndex)
        proxy.setFilterFixedString(columnValue)
        # Will return model index containing the primary key.
        matchingIndex = proxy.mapToSource(proxy.index(0, 0))

        return matchingIndex

    def _modelInstanceFromIds(self, ids):
        '''
        Returns the model instance based the value of its primary key.
        '''
        dbHandler = self._dbmodel()

        modelInstances = []

        for modelId in ids:
            modelObj = dbHandler.queryObject().filter(
                self._dbmodel.id == modelId).first()
            if not modelObj is None:
                modelInstances.append(modelObj)

        return modelInstances

    def _onRecordSelectedEntityBrowser(self, rec, row_number=-1):
        '''
        Slot raised when the user has clicked the select button
        in the 'EntityBrowser' dialog
        to add the selected record to the table's list.
        Add the record to the foreign key table using the mappings.
        '''
        # Check if the record exists using the primary key so as to ensure
        # only one instance is added to the table
        if isinstance(rec, int):
            recIndex = getIndex(self._recordIds(), rec)

            if recIndex != -1:
                return

            dbHandler = self._dbmodel()
            modelObj = dbHandler.queryObject().filter(
                self._dbmodel.id == rec).first()

        elif isinstance(rec, object):
            modelObj = rec

        else:
            return

        if modelObj is not None:
            # Raise before entity added signal
            self.beforeEntityAdded.emit(modelObj)

            # Validate for unique value configurations
            '''
            if not self._validate_unique_columns(modelObj, row_number):
                return
            '''

            if not self._supportsLists and self._tableModel.rowCount() > 0:
                self._removeRow(0)

            insert_position = self._insertModelToView(modelObj, row_number)

            if isinstance(rec, object):
                self._deferred_objects[insert_position] = modelObj

    def _validate_unique_columns(self, model, exclude_row=-1):
        """
        Loop through the attributes of the model to assert
        for existing row values that should be unique based on
        the configuration of unique columns.
        """
        for colIndex, replace in list(self._uniqueValueColIndices.items()):
            attrName = list(self._dbmodel.displayMapping().keys())[colIndex]
            attrValue = getattr(model, attrName)

            # Check to see if there are cell formatters so
            # that the correct value is searched for in the model
            if attrName in self._cell_formatters:
                attrValue = self._cell_formatters[attrName](attrValue)

            matchingIndex = self.searchModel(colIndex, attrValue)

            if matchingIndex.isValid() and matchingIndex.row() != exclude_row:
                if replace:
                    existingId = matchingIndex.data()

                    # Delete old record from db
                    entityModels = self._modelInstanceFromIds([existingId])

                    if len(entityModels) > 0:
                        entityModels[0].delete()

                    self._removeRow(matchingIndex.row())

                    return True

                else:
                    # Break. Do not add item to the list.
                    return False

        return True

    def _insertModelToView(self, model_obj, row_number=-1):
        """
        Insert the given database model instance into the view
        at the given row number position.
        """
        if row_number == -1:
            row_number = self._tableModel.rowCount()
            self._tableModel.insertRows(row_number, 1)

        # In some instances, we will need to get the model object with
        # backrefs included else exceptions will be raised on missing
        # attributes
        q_objs = self._modelInstanceFromIds([model_obj.id])
        if len(q_objs) == 0:
            return

        model_obj = q_objs[0]

        for i, attr in enumerate(self._entity_attrs):
            prop_idx = self._tableModel.index(row_number, i)
            attr_val = getattr(model_obj, attr)
            '''
            Check if there are display formatters and apply if one exists
            for the given attribute.
            '''
            if attr in self._cell_formatters:
                formatter = self._cell_formatters[attr]
                attr_val = formatter.format_column_value(attr_val)

            self._tableModel.setData(prop_idx, attr_val)

        # Raise signal once entity has been inserted
        self.afterEntityAdded.emit(model_obj, row_number)

        self._tbFKEntity.resizeColumnsToContents()

        return row_number

    def insert_model_to_table(self, model_obj, row_number=-1):
        """
         Insert the given database model instance into the view
         at the given row number position.
         """
        if row_number == -1:
            row_number = self._tableModel.rowCount()
            self._tableModel.insertRows(row_number, 1)
        # In some instances, we will need to get the model object with
        # backrefs included else exceptions will be raised on missing
        # attributes
        q_objs = self._modelInstanceFromIds([model_obj.id])

        if len(q_objs) == 0:
            return

        model_obj = q_objs[0]

        for i, attr in enumerate(self._entity_attrs):
            prop_idx = self._tableModel.index(row_number, i)
            attr_val = getattr(model_obj, attr)

            # Check if there are display formatters and apply if one exists
            # for the given attribute.

            if attr in self._cell_formatters:
                formatter = self._cell_formatters[attr]
                attr_val = formatter.format_column_value(attr_val)

            self._tableModel.setData(prop_idx, attr_val)

        #self._tbFKEntity.resizeColumnsToContents()
        self._tbFKEntity.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)

        return row_number

    def remove_rows(self):
        """
        Removes rows from the fk browser.
        """
        row_count = self._tbFKEntity.model().rowCount()

        self._tbFKEntity.model().removeRows(0, row_count)

    def vector_layer(self):
        """
        Returns a QgsVectorLayer based on the configuration information
        specified in the mapper including the system-wide data connection
        properties.
        """
        from stdm.data.pg_utils import vector_layer

        if self._dbmodel is None:
            msg = QApplication.translate(
                "ForeignKeyMapper",
                "Primary database model object not defined.")
            return None, msg

        filter_layer = vector_layer(self._entity.name)
        if filter_layer is None:
            msg = QApplication.translate(
                "ForeignKeyMapper",
                "Vector layer could not be constructed from the database table."
            )

            return None, msg

        if not filter_layer.isValid():
            trans_msg = QApplication.translate(
                "ForeignKeyMapper",
                "The vector layer for '{0}' table is invalid.")
            msg = trans_msg.format(self._entity.name)

            return None, msg

        return filter_layer, ""

    def onAddEntity(self):
        """
        Slot raised on selecting to add related entities that will be mapped to the primary
        database model instance.
        """
        self._entitySelector.buttonBox.button(
            QDialogButtonBox.Cancel).setVisible(False)

        # Clear any previous selections in the entity browser
        self._entitySelector.clear_selection()

        # Clear any previous notifications
        self._entitySelector.clear_notifications()

        self._entitySelector.exec_()
class GeometryDiffViewerDialog(QDialog):
    def __init__(self, geoms, crs, parent=None):
        super(GeometryDiffViewerDialog, self).__init__(parent)
        self.geoms = geoms
        self.crs = crs
        self.initGui()

    def initGui(self):
        layout = QVBoxLayout()
        self.tab = QTabWidget()
        self.table = QTableView()

        self.setLayout(layout)
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        settings = QSettings()
        self.canvas.enableAntiAliasing(
            settings.value("/qgis/enable_anti_aliasing", False, type=bool))
        self.canvas.useImageToRender(
            settings.value("/qgis/use_qimage_to_render", False, type=bool))
        self.canvas.mapSettings().setDestinationCrs(self.crs)
        action = settings.value("/qgis/wheel_action", 0, type=float)
        zoomFactor = settings.value("/qgis/zoom_factor", 2, type=float)
        self.canvas.setWheelAction(QgsMapCanvas.WheelAction(action),
                                   zoomFactor)
        self.panTool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.panTool)

        execute(self.createLayers)

        model = GeomDiffTableModel(self.data)
        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.table.resizeRowsToContents()
        self.tab.addTab(self.canvas, "Map view")
        self.tab.addTab(self.table, "Table view")
        layout.addWidget(self.tab)

        self.resize(600, 500)
        self.setWindowTitle("Geometry comparison")

    def createLayers(self):
        textGeometries = []
        for geom in self.geoms:
            text = geom.exportToWkt()
            valid = " -1234567890.,"
            text = "".join([c for c in text if c in valid])
            textGeometries.append(text.split(","))
        lines = difflib.Differ().compare(textGeometries[0], textGeometries[1])
        self.data = []
        for line in lines:
            if line.startswith("+"):
                self.data.append([None, line[2:]])
            if line.startswith("-"):
                self.data.append([line[2:], None])
            if line.startswith(" "):
                self.data.append([line[2:], line[2:]])
        types = [("LineString", lineBeforeStyle, lineAfterStyle),
                 ("Polygon", polygonBeforeStyle, polygonAfterStyle)]
        layers = []
        extent = self.geoms[0].boundingBox()
        for i, geom in enumerate(self.geoms):
            geomtype = types[int(geom.type() - 1)][0]
            style = types[int(geom.type() - 1)][i + 1]
            layer = loadLayerNoCrsDialog(
                geomtype + "?crs=" + self.crs.authid(), "layer", "memory")
            pr = layer.dataProvider()
            feat = QgsFeature()
            feat.setGeometry(geom)
            pr.addFeatures([feat])
            layer.loadNamedStyle(style)
            layer.updateExtents()
            layers.append(layer)
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            extent.combineExtentWith(geom.boundingBox())

        layer = loadLayerNoCrsDialog(
            "Point?crs=%s&field=changetype:string" % self.crs.authid(),
            "points", "memory")
        pr = layer.dataProvider()
        feats = []
        for coords in self.data:
            coord = coords[0] or coords[1]
            feat = QgsFeature()
            x, y = coord.strip().split(" ")
            x, y = (float(x), float(y))
            pt = QgsGeometry.fromPoint(QgsPoint(x, y))
            feat.setGeometry(pt)
            if coords[0] is None:
                changetype = "A"
            elif coords[1] is None:
                changetype = "R"
            else:
                changetype = "U"
            feat.setAttributes([changetype])
            feats.append(feat)

        pr.addFeatures(feats)
        layer.loadNamedStyle(pointsStyle)
        QgsMapLayerRegistry.instance().addMapLayer(layer, False)
        layers.append(layer)

        self.mapLayers = [QgsMapCanvasLayer(lay) for lay in layers]
        self.canvas.setLayerSet(self.mapLayers)
        self.canvas.setExtent(extent)
        self.canvas.refresh()

    def reject(self):
        QDialog.reject(self)
class GeometryDiffViewerDialog(QDialog):

    def __init__(self, geoms, crs, parent = None):
        super(GeometryDiffViewerDialog, self).__init__(parent)
        self.geoms = geoms
        self.crs = crs
        self.initGui()

    def initGui(self):
        layout = QVBoxLayout()
        self.tab = QTabWidget()
        self.table = QTableView()

        self.setLayout(layout)
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        settings = QSettings()
        self.canvas.enableAntiAliasing(settings.value("/qgis/enable_anti_aliasing", False, type = bool))
        self.canvas.useImageToRender(settings.value("/qgis/use_qimage_to_render", False, type = bool))
        self.canvas.mapSettings().setDestinationCrs(self.crs)
        action = settings.value("/qgis/wheel_action", 0, type = float)
        zoomFactor = settings.value("/qgis/zoom_factor", 2, type = float)
        self.canvas.setWheelAction(QgsMapCanvas.WheelAction(action), zoomFactor)
        self.panTool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.panTool)

        execute(self.createLayers)

        model = GeomDiffTableModel(self.data)
        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.table.resizeRowsToContents()
        self.tab.addTab(self.canvas, "Map view")
        self.tab.addTab(self.table, "Table view")
        layout.addWidget(self.tab)

        self.resize(600, 500)
        self.setWindowTitle("Geometry comparison")


    def createLayers(self):
        textGeometries = []
        for geom in self.geoms:
            text = geom.exportToWkt()
            valid = " -1234567890.,"
            text = "".join([c for c in text if c in valid])
            textGeometries.append(text.split(","))
        lines = difflib.Differ().compare(textGeometries[0], textGeometries[1])
        self.data = []
        for line in lines:
            if line.startswith("+"):
                self.data.append([None, line[2:]])
            if line.startswith("-"):
                self.data.append([line[2:], None])
            if line.startswith(" "):
                self.data.append([line[2:], line[2:]])
        types = [("LineString", lineBeforeStyle, lineAfterStyle),
                  ("Polygon", polygonBeforeStyle, polygonAfterStyle)]
        layers = []
        extent = self.geoms[0].boundingBox()
        for i, geom in enumerate(self.geoms):
            geomtype = types[int(geom.type() - 1)][0]
            style = types[int(geom.type() - 1)][i + 1]
            layer = loadLayerNoCrsDialog(geomtype + "?crs=" + self.crs.authid(), "layer", "memory")
            pr = layer.dataProvider()
            feat = QgsFeature()
            feat.setGeometry(geom)
            pr.addFeatures([feat])
            layer.loadNamedStyle(style)
            layer.updateExtents()
            layers.append(layer)
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            extent.combineExtentWith(geom.boundingBox())

        layer = loadLayerNoCrsDialog("Point?crs=%s&field=changetype:string" % self.crs.authid(), "points", "memory")
        pr = layer.dataProvider()
        feats = []
        for coords in self.data:
            coord = coords[0] or coords[1]
            feat = QgsFeature()
            x, y = coord.strip().split(" ")
            x, y = (float(x), float(y))
            pt = QgsGeometry.fromPoint(QgsPoint(x, y))
            feat.setGeometry(pt)
            if coords[0] is None:
                changetype = "A"
            elif coords[1] is None:
                changetype = "R"
            else:
                changetype = "U"
            feat.setAttributes([changetype])
            feats.append(feat)

        pr.addFeatures(feats)
        layer.loadNamedStyle(pointsStyle)
        QgsMapLayerRegistry.instance().addMapLayer(layer, False)
        layers.append(layer)

        self.mapLayers = [QgsMapCanvasLayer(lay) for lay in layers]
        self.canvas.setLayerSet(self.mapLayers)
        self.canvas.setExtent(extent)
        self.canvas.refresh()

    def reject(self):
        QDialog.reject(self)
class DisplayAequilibraEFormatsDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, iface):
        QtWidgets.QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        self.error = None

        self.error = None
        self.data_path, self.data_type = GetOutputFileName(
            self, 'AequilibraE custom formats',
            ["Aequilibrae dataset(*.aed)", "Aequilibrae matrix(*.aem)"],
            '.aed', standard_path())

        if self.data_type is None:
            self.error = 'Path provided is not a valid dataset'
            self.exit_with_error()

        self.data_type = self.data_type.upper()

        if self.data_type == 'AED':
            self.data_to_show = AequilibraEData()
        elif self.data_type == 'AEM':
            self.data_to_show = AequilibraeMatrix()

        try:
            self.data_to_show.load(self.data_path)
        except:
            self.error = 'Could not load dataset'
            self.exit_with_error()

        # Elements that will be used during the displaying
        self._layout = QVBoxLayout()
        self.table = QTableView()
        self._layout.addWidget(self.table)

        # Settings for displaying
        self.show_layout = QHBoxLayout()

        # Thousand separator
        self.thousand_separator = QCheckBox()
        self.thousand_separator.setChecked(True)
        self.thousand_separator.setText('Thousands separator')
        self.thousand_separator.toggled.connect(self.format_showing)
        self.show_layout.addWidget(self.thousand_separator)

        self.spacer = QSpacerItem(5, 0, QtWidgets.QSizePolicy.Expanding,
                                  QtWidgets.QSizePolicy.Minimum)
        self.show_layout.addItem(self.spacer)

        # Decimals
        txt = QLabel()
        txt.setText('Decimal places')
        self.show_layout.addWidget(txt)
        self.decimals = QSpinBox()
        self.decimals.valueChanged.connect(self.format_showing)
        self.decimals.setMinimum(0)
        self.decimals.setValue(4)
        self.decimals.setMaximum(10)

        self.show_layout.addWidget(self.decimals)
        self._layout.addItem(self.show_layout)

        # differentiates between matrix and dataset
        if self.data_type == 'AEM':
            self.data_to_show.computational_view([self.data_to_show.names[0]])
            # Matrices need cores and indices to be set as well
            self.mat_layout = QHBoxLayout()
            self.mat_list = QComboBox()
            for n in self.data_to_show.names:
                self.mat_list.addItem(n)

            self.mat_list.currentIndexChanged.connect(self.change_matrix_cores)
            self.mat_layout.addWidget(self.mat_list)

            self.idx_list = QComboBox()
            for i in self.data_to_show.index_names:
                self.idx_list.addItem(i)
            self.idx_list.currentIndexChanged.connect(self.change_matrix_cores)
            self.mat_layout.addWidget(self.idx_list)
            self._layout.addItem(self.mat_layout)
            self.change_matrix_cores()

        self.but_export = QPushButton()
        self.but_export.setText('Export')
        self.but_export.clicked.connect(self.export)

        self.but_close = QPushButton()
        self.but_close.clicked.connect(self.exit_procedure)
        self.but_close.setText('Close')

        self.but_layout = QHBoxLayout()
        self.but_layout.addWidget(self.but_export)
        self.but_layout.addWidget(self.but_close)

        self._layout.addItem(self.but_layout)

        # We chose to use QTableView. However, if we want to allow the user to edit the dataset
        # The we need to allow them to switch to the slower QTableWidget
        # Code below

        # self.table = QTableWidget(self.data_to_show.entries, self.data_to_show.num_fields)
        # self.table.setHorizontalHeaderLabels(self.data_to_show.fields)
        # self.table.setObjectName('data_viewer')
        #
        # self.table.setVerticalHeaderLabels([str(x) for x in self.data_to_show.index[:]])
        # self.table.clearContents()
        #
        # for i in range(self.data_to_show.entries):
        #     for j, f in enumerate(self.data_to_show.fields):
        #         item1 = QTableWidgetItem(str(self.data_to_show.data[f][i]))
        #         item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        #         self.table.setItem(i, j, item1)

        self.resize(700, 500)
        self.setLayout(self._layout)
        self.format_showing()

    def format_showing(self):
        decimals = self.decimals.value()
        separator = self.thousand_separator.isChecked()
        if isinstance(self.data_to_show, AequilibraeMatrix):
            m = NumpyModel(self.data_to_show, separator, decimals)
        else:
            m = DatabaseModel(self.data_to_show, separator, decimals)
        self.table.clearSpans()
        self.table.setModel(m)

    def change_matrix_cores(self):
        self.data_to_show.computational_view([self.mat_list.currentText()])
        self.data_to_show.set_index(self.data_to_show.index_names[0])
        self.format_showing()

    def export(self):
        new_name, file_type = GetOutputFileName(
            self, self.data_type, ["Comma-separated file(*.csv)"], ".csv",
            self.data_path)
        if new_name is not None:
            self.data_to_show.export(new_name)

    def exit_with_error(self):
        qgis.utils.iface.messageBar().pushMessage("Error:",
                                                  self.error,
                                                  level=1)
        self.exit_procedure()

    def exit_procedure(self):
        self.close()