def _load_fields_table(self):
        """Populate the table with the fields and the checkboxes
        """
        self.columns_table.clear()
        self.columns_table.setRowCount(0)
        self.columns_table.setColumnCount(2)

        self.columns_table.setHorizontalHeaderLabels(['Visible', 'Column'])

        excluded_fields = self._get_excluded_columns_list()

        row = 0
        for field in self.layer.fields():
            self.columns_table.insertRow(row)

            cb = QCheckBox()
            cb.setCheckState(Qt.Checked)
            if field.name() in excluded_fields:
                cb.setCheckState(Qt.Unchecked)

            self.columns_table.setCellWidget(row, 0, cb)

            item = QTableWidgetItem(field.name())
            self.columns_table.setItem(row, 1, item)

            row += 1

        self.columns_table.resizeColumnsToContents()
示例#2
0
 def carregaTabMats(self, tbMats):
     tableWidget = self.dlg.findChild(QTableWidget, 'tableWidget')
     tableWidget.setRowCount(0)
     tableWidget.setColumnCount(0)
     for i, tbMat in enumerate(tbMats):
         row = tableWidget.rowCount()
         tableWidget.insertRow(row)
         tableWidget.setColumnCount(len(tbMat))
         if row < 1:
             tableWidget.setHorizontalHeaderLabels(tbMat)
         else:
             for column, data in enumerate(tbMat):
                 if column == 0:
                     cell_widget = QWidget()
                     lay_out = QHBoxLayout(cell_widget)
                     chk_bx = QCheckBox()
                     if data in [1, '1', 't', 'True']:
                         chk_bx.setCheckState(QtCore.Qt.Checked)
                     else:
                         chk_bx.setCheckState(QtCore.Qt.Unchecked)
                     lay_out.addWidget(chk_bx)
                     lay_out.setAlignment(Qt.AlignCenter)
                     lay_out.setContentsMargins(0, 0, 0, 0)
                     cell_widget.setLayout(lay_out)
                     tableWidget.setCellWidget(row, 0, cell_widget)
                 else:
                     item = QTableWidgetItem("{}".format(data))  #:7.2f
                     item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                     tableWidget.setItem(row, column, item)
     #tableWidget.setHorizontalHeaderLabels(['On','DN','Diameter','Roughness','Pressure','Headloss','Reference'])
     #for i in range(1,4):
     #    tableWidget.resizeColumnToContents(i)
     tableWidget.removeRow(0)
     tableWidget.resizeColumnsToContents()
class LayerItemWidget(QWidget):
    def __init__(self, layer, parent=None):
        super(LayerItemWidget, self).__init__(parent)
        self.layer = layer
        self.layout = QHBoxLayout()
        self.check = QCheckBox()
        self.check.setText(layer.name())
        self.labelMetadata = QLabel()
        self.labelMetadata.setFixedWidth(50)
        self.labelData = QLabel()
        self.labelData.setFixedWidth(50)
        self.layout.addWidget(self.check)
        self.layout.addWidget(self.labelData)
        self.layout.addWidget(self.labelMetadata)
        self.setLayout(self.layout)

    def name(self):
        return self.layer.name()

    def iconPath(self, server):
        return os.path.join(os.path.dirname(os.path.dirname(__file__)),
                            "icons",
                            "%s.png" % server.__class__.__name__.lower()[:-6])

    def setMetadataPublished(self, server):
        self.labelMetadata.setPixmap(QPixmap(self.iconPath(server)))

    def setDataPublished(self, server):
        self.labelData.setPixmap(QPixmap(self.iconPath(server)))

    def checked(self):
        return self.check.isChecked()

    def setCheckState(self, state):
        self.check.setCheckState(state)
class ConnectCredentialsWidget(QWidget):
    rememberStateChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.leLogin = IconLineEdit(self)
        self.leLogin.setIcon(QIcon(os.path.join(iconsPath, "envelope.svg")))
        self.leLogin.setPlaceholderText("Email")

        self.lePassword = PasswordLineEdit(self)

        self.chkRemember = QCheckBox(self)
        self.chkRemember.setText("Remember me")

        self.lblResetPassword = QLabel(self)
        self.lblResetPassword.setAlignment(Qt.AlignCenter)
        self.lblResetPassword.setOpenExternalLinks(True)
        self.lblResetPassword.setTextInteractionFlags(Qt.LinksAccessibleByKeyboard | Qt.LinksAccessibleByMouse)
        self.lblResetPassword.setText("<html><head/><body><p><a href='https://boundlessgeo.auth0.com/login?client=rmtncamSKiwRBuVYTvFYJGtTspVuplMh'><span style='text-decoration: underline; color:#0000ff;'>Don't remember your password?</span></a></p></body></html>")

        self.lblRegister = QLabel(self)
        self.lblRegister.setAlignment(Qt.AlignCenter)
        self.lblRegister.setOpenExternalLinks(True)
        self.lblRegister.setTextInteractionFlags(Qt.LinksAccessibleByKeyboard | Qt.LinksAccessibleByMouse)
        self.lblRegister.setText("<html><head/><body><p><a href='https://connect.boundlessgeo.com'><span style='text-decoration: underline; color:#0000ff;'>Don't have an account?</span></a></p></body></html>")

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.leLogin)
        self.layout.addWidget(self.lePassword)
        self.layout.addWidget(self.chkRemember)
        self.layout.addWidget(self.lblResetPassword)
        self.layout.addWidget(self.lblRegister)
        self.setLayout(self.layout)

        self.chkRemember.stateChanged.connect(self.rememberCheckChanged)


    def login(self):
        return self.leLogin.text()

    def setLogin(self, login):
        self.leLogin.setText(login)

    def password(self):
        return self.lePassword.text()

    def setPassword(self, password):
        self.lePassword.setText(password)

    def remember(self):
        return self.chkRemember.isChecked()

    def setRemember(self, state):
        self.chkRemember.setCheckState(state)

    def rememberCheckChanged(self, state):
        self.rememberStateChanged.emit(state)
示例#5
0
 def btnIns_push(self):
     tableWidget = self.ui.tableWidget
     tableWidget.insertRow(tableWidget.currentRow() + 1)
     cell_widget = QWidget()
     lay_out = QHBoxLayout(cell_widget)
     chk_bx = QCheckBox()
     chk_bx.setCheckState(QtCore.Qt.Checked)
     lay_out.addWidget(chk_bx)
     lay_out.setAlignment(Qt.AlignCenter)
     lay_out.setContentsMargins(0, 0, 0, 0)
     cell_widget.setLayout(lay_out)
     tableWidget.setCellWidget(tableWidget.currentRow() + 1, 0, cell_widget)
示例#6
0
    def widgetFromParameter(self, param):
        paramtype = param["type"]
        if paramtype == FILES:

            def edit(textbox):
                f = QFileDialog.getOpenFileNames(self, "Select file", "",
                                                 "*.*")
                if f:
                    textbox.value = ",".join(f)

            return TextBoxWithLink("Browse", edit, None, True)
        elif paramtype == FOLDER:

            def edit(textbox):
                f = QFileDialog.getExistingDirectory(self, "Select folder", "")
                if f:
                    textbox.value = f

            return TextBoxWithLink("Browse", edit, None, True)
        elif paramtype == BOOL:
            check = QCheckBox(param["label"])
            if param["default"]:
                check.setCheckState(Qt.Checked)
            else:
                check.setCheckState(Qt.Unchecked)
            return check
        elif paramtype == CHOICE:
            combo = QComboBox()
            for option in param["options"]:
                combo.addItem(option)
            idx = combo.findText(str(param["default"]))
            combo.setCurrentIndex(idx)
            return combo
        elif paramtype == TEXT:
            textEdit = QTextEdit()
            textEdit.setPlainText(param["default"])
            return textEdit
        elif paramtype == VECTOR:
            combo = QgsMapLayerComboBox()
            combo.setFilters(QgsMapLayerProxyModel.VectorLayer)
            return combo
        elif paramtype == RASTER:
            combo = QgsMapLayerComboBox()
            combo.setFilters(QgsMapLayerProxyModel.RasterLayer)
            return combo
        elif paramtype == PASSWORD:
            lineEdit = QLineEdit()
            lineEdit.setEchoMode(QLineEdit.Password)
            return lineEdit
        else:
            lineEdit = QLineEdit()
            lineEdit.setText(str(param["default"]))
            return lineEdit
示例#7
0
 def ImportaTubos(self):
     #MsgTxt=self.tr(u'Importa tubos!')
     #QMessageBox.information(None,self.SETTINGS,MsgTxt)
     self.table = self.ui.tableWidget
     prjfi = os.path.splitext(QgsProject.instance().fileName())[0] + '.csv'
     path, __ = QFileDialog.getOpenFileName(self, 'Open File', prjfi,
                                            'CSV(*.csv)')
     if path:
         if os.path.exists(path):
             with open(str(path), 'r', newline='') as stream:
                 self.table.setRowCount(0)
                 self.table.setColumnCount(0)
                 for rowdata in csv.reader(stream):
                     self.table.setColumnCount(len(rowdata))
                     row = self.table.rowCount()
                     self.table.insertRow(row)
                     if row < 1:
                         self.table.setHorizontalHeaderLabels(rowdata)
                     else:
                         for column, data in enumerate(rowdata):
                             valor = data  #.decode('utf8')
                             if column == 0:
                                 cell_widget = QWidget()
                                 lay_out = QHBoxLayout(cell_widget)
                                 chk_bx = QCheckBox()
                                 if valor in [1, '1', 't', 'True']:
                                     chk_bx.setCheckState(QtCore.Qt.Checked)
                                 else:
                                     chk_bx.setCheckState(
                                         QtCore.Qt.Unchecked)
                                 lay_out.addWidget(chk_bx)
                                 lay_out.setAlignment(Qt.AlignCenter)
                                 lay_out.setContentsMargins(0, 0, 0, 0)
                                 cell_widget.setLayout(lay_out)
                                 self.table.setCellWidget(
                                     row, 0, cell_widget)
                             else:
                                 item = QTableWidgetItem(
                                     data)  #.decode('utf8')
                                 item.setTextAlignment(Qt.AlignVCenter
                                                       | Qt.AlignRight)
                                 self.table.setItem(row, column, item)
                 #self.table.setHorizontalHeaderLabels(['On','DN','Diameter','Roughness','Pressure','Referencia'])
                 #for i in range(1,4):
                 #    self.table.resizeColumnToContents(i)
                 self.table.removeRow(
                     0
                 )  #Remove a primeira linha em branco auxiliar para inserir o cabecalho
                 self.table.resizeColumnsToContents(
                 )  #Para ajustar todas as colunas de vez
示例#8
0
class LayerItemWidget(QWidget):
    def __init__(self, layer, parent=None):
        super(LayerItemWidget, self).__init__(parent)
        self.layer = layer
        self.layout = QHBoxLayout()
        self.check = QCheckBox()
        self.check.setText(layer.name())
        if layer.type() == layer.VectorLayer:
            self.check.setIcon(
                QgsApplication().getThemeIcon('/mIconLineLayer.svg'))
        else:
            self.check.setIcon(
                QgsApplication().getThemeIcon('/mIconRaster.svg'))
        self.labelMetadata = QLabel()
        self.labelMetadata.setFixedWidth(50)
        self.labelData = QLabel()
        self.labelData.setFixedWidth(50)
        self.layout.addWidget(self.check)
        self.layout.addWidget(self.labelData)
        self.layout.addWidget(self.labelMetadata)
        self.setLayout(self.layout)

    def name(self):
        return self.layer.name()

    @staticmethod
    def setIcon(label, server):
        pixmap = QPixmap(
            files.getIconPath(server.__class__.__name__.lower()[:-6]))
        label.setPixmap(pixmap)

    def setMetadataPublished(self, server):
        self.setIcon(self.labelMetadata, server)

    def setDataPublished(self, server):
        self.setIcon(self.labelData, server)

    def checked(self):
        return self.check.isChecked()

    def setCheckState(self, state):
        self.check.setCheckState(state)
class ItemWidgetBase(QFrame):

    checkedStateChanged = pyqtSignal()
    thumbnailChanged = pyqtSignal()

    def __init__(self, item):
        QFrame.__init__(self)
        self.item = item
        self.is_updating_checkbox = False
        self.setMouseTracking(True)
        self.setStyleSheet("ItemWidgetBase{border: 2px solid transparent;}")

    def _setup_ui(self, text, thumbnailurl):

        self.lockLabel = QLabel()
        iconSize = QSize(16, 16)
        self.lockLabel.setPixmap(LOCK_ICON.pixmap(iconSize))
        self.checkBox = QCheckBox("")
        self.checkBox.clicked.connect(self.check_box_state_changed)
        self.nameLabel = QLabel(text)
        self.iconLabel = QLabel()
        self.labelZoomTo = QLabel()
        self.labelZoomTo.setPixmap(ZOOMTO_ICON.pixmap(QSize(18, 18)))
        self.labelZoomTo.setToolTip("Zoom to extent")
        self.labelZoomTo.mousePressEvent = self.zoom_to_extent
        self.labelAddPreview = QLabel()
        self.labelAddPreview.setPixmap(ADD_PREVIEW_ICON.pixmap(QSize(18, 18)))
        self.labelAddPreview.setToolTip("Add preview layer to map")
        self.labelAddPreview.mousePressEvent = self._add_preview_clicked

        layout = QHBoxLayout()
        layout.setMargin(0)
        layout.addWidget(self.checkBox)
        layout.addWidget(self.lockLabel)
        pixmap = QPixmap(PLACEHOLDER_THUMB, "SVG")
        self.thumbnail = None
        thumb = pixmap.scaled(48, 48, Qt.KeepAspectRatio,
                              Qt.SmoothTransformation)
        self.iconLabel.setPixmap(thumb)
        self.iconLabel.setFixedSize(48, 48)
        layout.addWidget(self.iconLabel)
        if thumbnailurl is not None:
            download_thumbnail(thumbnailurl, self)
        layout.addWidget(self.nameLabel)
        layout.addStretch()
        layout.addWidget(self.labelZoomTo)
        layout.addWidget(self.labelAddPreview)
        layout.addSpacing(10)
        self.setLayout(layout)

        self.footprint = QgsRubberBand(iface.mapCanvas(),
                                       QgsWkbTypes.PolygonGeometry)
        self.footprint.setStrokeColor(PLANET_COLOR)
        self.footprint.setWidth(2)

    def set_thumbnail(self, img):
        self.thumbnail = QPixmap(img)
        thumb = self.thumbnail.scaled(48, 48, Qt.KeepAspectRatio,
                                      Qt.SmoothTransformation)
        self.iconLabel.setPixmap(thumb)
        self.thumbnailChanged.emit()

    def is_selected(self):
        return self.checkBox.checkState() == Qt.Checked

    def _geom_bbox_in_project_crs(self):
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem("EPSG:4326"),
            QgsProject.instance().crs(),
            QgsProject.instance(),
        )
        return transform.transformBoundingBox(self.geom.boundingBox())

    def _geom_in_project_crs(self):
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem("EPSG:4326"),
            QgsProject.instance().crs(),
            QgsProject.instance(),
        )
        geom = QgsGeometry(self.geom)
        geom.transform(transform)
        return geom

    def show_footprint(self):
        self.footprint.setToGeometry(self._geom_in_project_crs())

    def hide_footprint(self):
        self.footprint.reset(QgsWkbTypes.PolygonGeometry)

    def enterEvent(self, event):
        self.setStyleSheet(
            "ItemWidgetBase{border: 2px solid rgb(0, 157, 165);}")
        self.show_footprint()

    def leaveEvent(self, event):
        self.setStyleSheet("ItemWidgetBase{border: 2px solid transparent;}")
        self.hide_footprint()

    def zoom_to_extent(self, evt):
        rect = QgsRectangle(self._geom_bbox_in_project_crs())
        rect.scale(1.05)
        iface.mapCanvas().setExtent(rect)
        iface.mapCanvas().refresh()

    def _add_preview_clicked(self, evt):
        self.add_preview()

    @waitcursor
    def add_preview(self):
        send_analytics_for_preview(self.item.images())
        create_preview_group(self.name(), self.item.images())

    def check_box_state_changed(self):
        self.update_children_items()
        self.update_parent_item()
        self.checkedStateChanged.emit()

    def update_parent_item(self):
        parent = self.item.parent()
        if parent is not None:
            w = parent.treeWidget().itemWidget(parent, 0)
            w.update_checkbox()

    def update_children_items(self):
        total = self.item.childCount()
        if self.checkBox.isTristate():
            self.checkBox.setTristate(False)
            self.checkBox.setChecked(False)
        for i in range(total):
            w = self.item.treeWidget().itemWidget(self.item.child(i), 0)
            w.set_checked(self.checkBox.isChecked())

    def update_checkbox(self):
        selected = 0
        total = self.item.childCount()
        for i in range(total):
            w = self.item.treeWidget().itemWidget(self.item.child(i), 0)
            if w.is_selected():
                selected += 1
        if selected == total:
            self.checkBox.setTristate(False)
            self.checkBox.setCheckState(Qt.Checked)
        elif selected == 0:
            self.checkBox.setTristate(False)
            self.checkBox.setCheckState(Qt.Unchecked)
        else:
            self.checkBox.setTristate(True)
            self.checkBox.setCheckState(Qt.PartiallyChecked)

    def set_checked(self, checked):
        self.checkBox.setChecked(checked)
        self.update_children_items()

    def update_thumbnail(self):
        thumbnails = self.scene_thumbnails()
        if thumbnails and None not in thumbnails:
            bboxes = [img[GEOMETRY] for img in self.item.images()]
            pixmap = createCompoundThumbnail(bboxes, thumbnails)
            thumb = pixmap.scaled(48, 48, Qt.KeepAspectRatio,
                                  Qt.SmoothTransformation)
            self.iconLabel.setPixmap(thumb)
            self.thumbnailChanged.emit()

    def scene_thumbnails(self):
        thumbnails = []
        try:
            for i in range(self.item.childCount()):
                w = self.item.treeWidget().itemWidget(self.item.child(i), 0)
                thumbnails.extend(w.scene_thumbnails())
        except RuntimeError:
            # item might not exist anymore. In this case, we just return
            # an empty list
            pass
        return thumbnails
示例#10
0
class LayerItemWidget(QWidget):
    def __init__(self, layer, parent=None):
        super(LayerItemWidget, self).__init__(parent)
        self._name = layer.name()
        self._id = layer.id()
        self._checkbox = QCheckBox()
        self._checkbox.setText(self._name)
        if layer.type() == layer.VectorLayer:
            self._checkbox.setIcon(QgsApplication.getThemeIcon('/mIconLineLayer.svg'))
        else:
            self._checkbox.setIcon(QgsApplication.getThemeIcon('/mIconRaster.svg'))
        self._metalabel = QLabel()
        self._metalabel.setFixedWidth(20)
        self._datalabel = QLabel()
        self._datalabel.setFixedWidth(20)
        layout = QHBoxLayout()
        layout.addWidget(self._checkbox)
        layout.addWidget(self._datalabel)
        layout.addWidget(self._metalabel)
        self.setLayout(layout)

    @property
    def name(self):
        """ Returns the corresponding layer name of the current list widget item. """
        return self._name

    @property
    def id(self):
        """ Returns the QGIS layer ID of the current list widget item. """
        return self._id

    @staticmethod
    def _setIcon(label, server) -> bool:
        """ Sets the server icon on the layer item widget if it has been published to that server.

        :returns:   True if the icon was set, False if it was not (or removed).
        """
        if not isinstance(server, manager.bases.AbstractServer):
            if label.pixmap():
                # Remove existing pixmap
                label.pixmap().swap(QPixmap())
            return False
        server_widget = server.__class__.getWidgetClass()
        pixmap = server_widget.getPngIcon() if server_widget else QPixmap()
        if not pixmap.isNull():
            pixmap = pixmap.scaled(label.width(), label.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        label.setPixmap(pixmap)
        return not pixmap.isNull()

    def setMetadataPublished(self, server):
        if self._setIcon(self._metalabel, server):
            self._metalabel.setToolTip(f"Metadata published to '{server.serverName}'")
        else:
            self._metalabel.setToolTip('')

    def setDataPublished(self, server):
        if self._setIcon(self._datalabel, server):
            self._datalabel.setToolTip(f"Geodata published to '{server.serverName}'")
        else:
            self._datalabel.setToolTip('')

    @property
    def checked(self) -> bool:
        """ Returns True if the list widget item checkbox is in a checked state. """
        return self._checkbox.isChecked()

    def setCheckbox(self, state: bool):
        self._checkbox.setCheckState(Qt.Checked if state else Qt.Unchecked)
示例#11
0
    def __update_available_error_data(self):
        self.tbw_errors.setUpdatesEnabled(
            False)  # Don't render until we're ready

        # Save selection before clearing table to restate it later (if needed)
        self.__update_selected_item()

        self.tbw_errors.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        self.tbw_errors.clear()
        self.tbw_errors.blockSignals(False)

        self.tbw_errors.setHorizontalHeaderLabels(self.__column_labels)

        # Filter by search text
        list_errors = self.__filter_by_search_text(self.txt_search.text())
        self.tbw_errors.setRowCount(len(list_errors))
        row = 0

        for feature in list_errors:
            # 1) Fixed error checkbox
            widget = QWidget()
            checkbox = QCheckBox()
            checkbox.setCheckState(Qt.Checked if self.__controller.
                                   is_fixed_error(feature) else Qt.Unchecked)
            checkbox.setStyleSheet('background: white;')
            checkbox.setEnabled(not self.__controller.is_exception(feature)
                                )  # Exceptions cannot be fixed
            checkbox.setToolTip(
                QCoreApplication.translate(
                    "QualityRulesErrorResultsPanelWidget",
                    "Is the error fixed?"))
            layout = QHBoxLayout(widget)
            layout.addWidget(checkbox)
            layout.setAlignment(Qt.AlignCenter)
            layout.setContentsMargins(0, 0, 0, 0)
            checkbox.stateChanged.connect(
                partial(self.__error_state_changed, row))
            self.tbw_errors.setCellWidget(row, CHECK_COLUMN, widget)

            # 2) Object UUIDs
            uuids = self.__controller.uuid_objs(feature)
            uuid_item = QTableWidgetItem(uuids)
            uuid_item.setData(Qt.UserRole,
                              self.__controller.error_t_id(feature))
            ili_name = self.__controller.ili_obj_name(feature)
            uuid_item.setData(
                Qt.ToolTipRole, "UUIDs ({}):\n{}".format(ili_name, uuids)
                if ili_name else "UUIDs:\n{}".format(uuids))
            self.tbw_errors.setItem(row, UUIDS_COLUMN, uuid_item)

            # 3) Error type code
            error_type_code, error_type_display = self.__controller.error_type_code_and_display(
                feature)
            error_type_item = QTableWidgetItem(error_type_code)
            error_type_item.setData(
                Qt.ToolTipRole, "{}\n({})".format(error_type_display,
                                                  error_type_code))
            self.tbw_errors.setItem(row, QRE_COLUMN, error_type_item)

            # 4) Details + Values
            details = self.__controller.error_details_and_values(feature)
            error_details_item = QTableWidgetItem(details)
            error_details_item.setData(Qt.ToolTipRole, details)
            self.tbw_errors.setItem(row, DETAILS_COLUMN, error_details_item)

            self.__set_row_color_by_state(
                row, self.__controller.error_state(feature))

            row += 1

        # Set selection
        self.tbw_errors.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        item = self.__get_item_by_t_id(self.__selected_item)
        if item:
            item.setSelected(True)
        self.tbw_errors.blockSignals(False)

        self.tbw_errors.setUpdatesEnabled(True)  # Now render!
class LinearBarcodeLayoutItemWidget(QgsLayoutItemBaseWidget):  # pylint: disable=too-few-public-methods
    """Widget for configuring a LinearBarcodeLayoutItem."""
    def __init__(self, parent, layout_object):
        super().__init__(parent, layout_object)
        self._barcode_item = layout_object
        self.message_bar = None

        self.setPanelTitle(self.tr('Linear Barcode Properties'))
        self._init_widgets(layout_object)
        self._current_meta = self._barcode_cbo.current_metadata()
        self._update_gui_values()

    def _init_widgets(self, layout_object):
        """Initialize widgets"""
        lbl_title = QLabel()
        lbl_title.setStyleSheet(
            'padding: 2px; font-weight: bold; background-color: '
            'rgb(200, 200, 200);')
        lbl_title.setText(self.tr('Linear Barcode'))
        self._cd_value_widget = CodeValueWidget(self)
        self._cd_value_widget.value_changed.connect(
            self._on_code_value_changed)
        value_groupbox = QgsCollapsibleGroupBoxBasic(self.tr('Data'))
        gp_layout = QVBoxLayout()
        gp_layout.setContentsMargins(0, 0, 0, 0)
        gp_layout.addWidget(self._cd_value_widget)
        value_groupbox.setLayout(gp_layout)

        # Barcode properties
        barcode_props_groupbox = QgsCollapsibleGroupBoxBasic(
            self.tr('Properties'))
        barcode_props_layout = QGridLayout()

        lbl_barcode_type = QLabel(self.tr('Linear barcode type'))
        self._barcode_cbo = LinearMetadataCombobox()
        self._barcode_cbo.metadata_changed.connect(
            self._on_linear_type_changed)
        barcode_props_layout.addWidget(lbl_barcode_type, 0, 0)
        barcode_props_layout.addWidget(self._barcode_cbo, 0, 1)
        self._chk_checksum = QCheckBox(self.tr('Add checksum'))
        self._chk_checksum.stateChanged.connect(self._on_add_checksum)
        barcode_props_layout.addWidget(self._chk_checksum, 1, 0, 1, 2)
        self._chk_render_txt = QCheckBox(self.tr('Render barcode text'))
        self._chk_render_txt.stateChanged.connect(self._on_render_text_changed)
        barcode_props_layout.addWidget(self._chk_render_txt, 2, 0, 1, 2)
        barcode_props_layout.setColumnStretch(1, 1)

        barcode_props_groupbox.setLayout(barcode_props_layout)

        # Properties widget
        self._prop_widget = QgsLayoutItemPropertiesWidget(self, layout_object)
        self._prop_widget.showBackgroundGroup(False)

        # Add widgets to layout
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(lbl_title)
        layout.addWidget(barcode_props_groupbox)
        layout.addWidget(value_groupbox)
        layout.addWidget(self._prop_widget)

        # Set layout
        self.setLayout(layout)

    def setDesignerInterface(self, iface):
        """
        Use layout iface to set the message_bar.
        """
        super().setDesignerInterface(iface)
        self.message_bar = iface.messageBar()

    def metadata(self, metadata_id):
        """
        Gets the metadata object that corresponds to the given id.
        :param metadata_id: Metadata id.
        :type metadata_id: str
        :return: Returns the metadata object corresponding to the
        given id.
        :rtype: AbstractLinearBarcodeMetadata
        """
        reg = LinearBarcodeMetadataRegistry.instance()

        return reg.metadata_by_typeid(metadata_id)

    def setNewItem(self, item):
        """
        Set widget properties to sync with item properties.
        """
        if item.type() != LINEAR_BARCODE_TYPE:
            return False

        self._barcode_item = item
        self._prop_widget.setItem(self._barcode_item)
        self._update_gui_values()

        return True

    def _on_linear_type_changed(self, metadata_id):
        """
        Slot raised when the linear barcode type has been changed.
        """
        meta = self.metadata(metadata_id)
        if meta is None:
            return

        self._current_meta = meta
        self._adapt_ui_item_checksum_properties()
        self.set_barcode_data()

    def _adapt_ui_item_checksum_properties(self):
        """
        Update UI and barcode item properties based on the properties of the
        current metadata object.
        """
        if self._current_meta is None:
            return

        if self._current_meta.supports_manual_checksum():
            self._barcode_item.supports_manual_checksum = True
            self._chk_checksum.setEnabled(True)
            # Set check status based on barcode properties
            if self._barcode_item.add_checksum:
                self._chk_checksum.setCheckState(Qt.Checked)
            else:
                self._chk_checksum.setCheckState(Qt.Unchecked)
        else:
            self._barcode_item.supports_manual_checksum = False
            self._chk_checksum.setEnabled(False)
            self._barcode_item.add_checksum = False
            if self._current_meta.is_checksum_automatic():
                self._chk_checksum.setCheckState(Qt.Checked)
            else:
                self._chk_checksum.setCheckState(Qt.Unchecked)

    def _on_add_checksum(self, state):
        """
        Slot raised to add checksum to the barcode data.
        """
        add_checksum = False
        if state == Qt.Checked:
            add_checksum = True

        self._barcode_item.beginCommand(self.tr('Change add checksum'),
                                        QgsLayoutItem.UndoCustomCommand)
        self._barcode_item.blockSignals(True)
        self._barcode_item.add_checksum = add_checksum
        self._barcode_item.blockSignals(False)
        self._barcode_item.endCommand()

    def _on_code_value_changed(self, value):
        """
        Slot raised when the barcode value changes.
        """
        self.set_barcode_data()

    def set_barcode_data(self):
        """
        Assert if characters (computed from the expression) are valid. If
        not, remove invalid characters then check if the maximum number of
        characters are within the maximum set for the given linear barcode
        type.
        """
        # Flag for the validity of barcode data
        is_invalid = False
        if self._current_meta is None:
            return

        user_value = self._cd_value_widget.code_value
        cd_val = self._barcode_item.evaluate_expression(user_value)

        if not cd_val:
            return

        # Check valid characters
        valid_chars = []
        for ch in cd_val:
            if self._current_meta.is_character_allowed(ch):
                valid_chars.append(ch)

        sanitized_txt = ''.join(valid_chars)

        # Notify user if there were invalid chars
        if len(sanitized_txt) != len(cd_val):
            self.add_warning_message(
                self.tr('Barcode data contains invalid characters.'))
            is_invalid = True

        cd_val = sanitized_txt
        # Check max length
        max_length = self._current_meta.max_input_length()
        if max_length != -1 and len(cd_val) > max_length:
            self.add_warning_message(
                self.tr('Barcode data cannot exceed the maximum length of '
                        '{0} characters for {1} linear barcode type.'.format(
                            max_length, self._current_meta.display_name())))
            is_invalid = True

        # Highlight barcode data based on validity of the input
        self._cd_value_widget.highlight_invalid_data(is_invalid)

        if is_invalid:  # pylint: disable=no-else-return
            return
        else:
            # Remove any warning items if still visible
            # Check if message_bar has already been initialized
            if self.message_bar is not None:
                self.message_bar.clearWidgets()

        # Set barcode value
        self._barcode_item.beginCommand(self.tr('Change code value'),
                                        QgsLayoutItem.UndoLabelText)
        self._barcode_item.blockSignals(True)
        try:
            self._barcode_item.barcode_type = self._current_meta.type_id()
            self._barcode_item.code_value = user_value
        except BarcodeException as bc_ex:
            self.add_warning_message(str(bc_ex))
            is_invalid = True
        self._barcode_item.blockSignals(False)
        self._barcode_item.endCommand()

    def _on_render_text_changed(self, state):
        """
        Slot raised when render_text has been checked/unchecked.
        """
        render_text = False
        if state == Qt.Checked:
            render_text = True

        self._barcode_item.beginCommand(self.tr('Change render text'),
                                        QgsLayoutItem.UndoCustomCommand)
        self._barcode_item.blockSignals(True)
        self._barcode_item.render_text = render_text
        self._barcode_item.blockSignals(False)
        self._barcode_item.endCommand()

    def _update_gui_values(self):
        """
        Update gui items based on the item properties.
        """
        self._current_meta = self.metadata(self._barcode_item.barcode_type)

        # Barcode type in combobox
        self._barcode_cbo.blockSignals(True)
        self._barcode_cbo.set_current_metadata(self._barcode_item.barcode_type)
        self._barcode_cbo.blockSignals(False)

        # Checksum property
        self._adapt_ui_item_checksum_properties()

        # Render text property
        self._chk_render_txt.blockSignals(True)
        if self._barcode_item.render_text:
            self._chk_render_txt.setCheckState(Qt.Checked)
        else:
            self._chk_render_txt.setCheckState(Qt.Unchecked)
        self._chk_render_txt.blockSignals(False)

        # Barcode value (which could also be an expression)
        self._cd_value_widget.block_value_widget_signals(True)
        self._cd_value_widget.code_value = self._barcode_item.code_value
        self._cd_value_widget.value_text_edit.moveCursor(
            QTextCursor.End, QTextCursor.MoveAnchor)
        self._cd_value_widget.block_value_widget_signals(False)

        # Now set barcode data
        self.set_barcode_data()

    def add_warning_message(self, msg):
        """
        Add warning message to the layout interface.
        :param msg: Warning message.
        :type msg: str
        """
        self.message_bar.pushWarning(self.tr('Linear Barcode'), msg)