Ejemplo n.º 1
0
    def setupTabs(self):
        """ Setup the various tabs in the AddressWidget. """
        groups = ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VW", "XYZ"]

        for group in groups:
            proxyModel = QSortFilterProxyModel(self)
            proxyModel.setSourceModel(self.tableModel)
            proxyModel.setDynamicSortFilter(True)

            tableView = QTableView()
            tableView.setModel(proxyModel)
            tableView.setSortingEnabled(True)
            tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
            tableView.horizontalHeader().setStretchLastSection(True)
            tableView.verticalHeader().hide()
            tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
            tableView.setSelectionMode(QAbstractItemView.SingleSelection)

            # This here be the magic: we use the group name (e.g. "ABC") to
            # build the regex for the QSortFilterProxyModel for the group's
            # tab. The regex will end up looking like "^[ABC].*", only
            # allowing this tab to display items where the name starts with
            # "A", "B", or "C". Notice that we set it to be case-insensitive.
            reFilter = "^[%s].*" % group

            proxyModel.setFilterRegExp(QRegExp(reFilter, Qt.CaseInsensitive))
            proxyModel.setFilterKeyColumn(0) # Filter on the "name" column
            proxyModel.sort(0, Qt.AscendingOrder)

            # This prevents an application crash (see: http://www.qtcentre.org/threads/58874-QListView-SelectionModel-selectionChanged-Crash)
            viewselectionmodel = tableView.selectionModel()
            tableView.selectionModel().selectionChanged.connect(self.selectionChanged)

            self.addTab(tableView, group)
Ejemplo n.º 2
0
    def setupTabs(self):
        """ Setup the various tabs in the AddressWidget. """
        groups = ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VW", "XYZ"]

        for group in groups:
            proxyModel = QSortFilterProxyModel(self)
            proxyModel.setSourceModel(self.tableModel)
            proxyModel.setDynamicSortFilter(True)

            tableView = QTableView()
            tableView.setModel(proxyModel)
            tableView.setSortingEnabled(True)
            tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
            tableView.horizontalHeader().setStretchLastSection(True)
            tableView.verticalHeader().hide()
            tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
            tableView.setSelectionMode(QAbstractItemView.SingleSelection)

            # This here be the magic: we use the group name (e.g. "ABC") to
            # build the regex for the QSortFilterProxyModel for the group's
            # tab. The regex will end up looking like "^[ABC].*", only
            # allowing this tab to display items where the name starts with
            # "A", "B", or "C". Notice that we set it to be case-insensitive.
            reFilter = "^[%s].*" % group

            proxyModel.setFilterRegExp(QRegExp(reFilter, Qt.CaseInsensitive))
            proxyModel.setFilterKeyColumn(0)  # Filter on the "name" column
            proxyModel.sort(0, Qt.AscendingOrder)

            # This prevents an application crash (see: http://www.qtcentre.org/threads/58874-QListView-SelectionModel-selectionChanged-Crash)
            viewselectionmodel = tableView.selectionModel()
            tableView.selectionModel().selectionChanged.connect(
                self.selectionChanged)

            self.addTab(tableView, group)
Ejemplo n.º 3
0
class QFilteredComboBox(QComboBox):
    def __init__(
        self,
        parent=None,
        include_targets=True,
        include_airbases=True,
        include_frontlines=True,
        include_units=True,
        include_enemy=True,
        include_friendly=True,
    ):
        super(QFilteredComboBox, self).__init__(parent)

        self.setFocusPolicy(Qt.StrongFocus)
        self.setEditable(True)
        self.completer = QCompleter(self)

        self.include_targets = include_targets
        self.include_airbases = include_airbases
        self.include_frontlines = include_frontlines
        self.include_units = include_units
        self.include_enemy = include_enemy
        self.include_friendly = include_friendly

        # always show all completions
        self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.pFilterModel = QSortFilterProxyModel(self)
        self.pFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)

        self.completer.setPopup(self.view())

        self.setCompleter(self.completer)

        self.lineEdit().textEdited.connect(self.pFilterModel.setFilterFixedString)
        self.completer.activated.connect(self.setTextIfCompleterIsClicked)

    def setModel(self, model):
        super(QFilteredComboBox, self).setModel(model)
        self.pFilterModel.setSourceModel(model)
        self.completer.setModel(self.pFilterModel)
        self.model().sort(0)

    def setModelColumn(self, column):
        self.completer.setCompletionColumn(column)
        self.pFilterModel.setFilterKeyColumn(column)
        super(QFilteredComboBox, self).setModelColumn(column)

    def view(self):
        return self.completer.popup()

    def index(self):
        return self.currentIndex()

    def setTextIfCompleterIsClicked(self, text):
        if text:
            index = self.findText(text)
            self.setCurrentIndex(index)
Ejemplo n.º 4
0
    def setupTable(self):
        proxyModel = QSortFilterProxyModel(self)
        proxyModel.setSourceModel(self.tableModel)
        proxyModel.setDynamicSortFilter(True)

        self.tableView.setModel(proxyModel)
        self.tableView.setSortingEnabled(True)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.verticalHeader().hide()
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)

        proxyModel.setFilterKeyColumn(0)  # Filter on the "name" column
        proxyModel.sort(0, Qt.AscendingOrder)
        viewselectionmodel = self.tableView.selectionModel()
        self.tableView.selectionModel().selectionChanged.connect(self.selectionChanged)
Ejemplo n.º 5
0
    def setupTable(self):
        proxyModel = QSortFilterProxyModel(self)
        proxyModel.setSourceModel(self.tableModel)
        proxyModel.setDynamicSortFilter(True)

        self.tableView.setModel(proxyModel)
        self.tableView.setSortingEnabled(True)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.verticalHeader().hide()
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)

        proxyModel.setFilterKeyColumn(0)  # Filter on the "name" column
        proxyModel.sort(0, Qt.AscendingOrder)
        viewselectionmodel = self.tableView.selectionModel()
        self.tableView.selectionModel().selectionChanged.connect(
            self.selectionChanged)
Ejemplo n.º 6
0
class Ui_Main(object):
    def setupUi(self, Main):
        if not Main.objectName():
            Main.setObjectName(u"Main")
        Main.resize(718, 453)
        Main.setMinimumSize(QSize(2018, 1053))

        Main.setStyleSheet(u"")
        self.centralwidget = QWidget(Main)
        self.centralwidget.setObjectName(u"centralwidget")

        self.centralwidget.setMinimumSize(QSize(2018, 1053))

        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.topbar_menu = QFrame(self.centralwidget)
        self.topbar_menu.setObjectName(u"topbar_menu")
        self.topbar_menu.setMinimumSize(QSize(20, 148))
        self.topbar_menu.setMaximumSize(QSize(16777215, 148))
        self.topbar_menu.setCursor(QCursor(Qt.ArrowCursor))
        self.topbar_menu.setStyleSheet(u"background-color: black;")
        self.topbar_menu.setFrameShape(QFrame.WinPanel)
        self.topbar_menu.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_2 = QHBoxLayout(self.topbar_menu)
        self.horizontalLayout_2.setSpacing(0)
        self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.slideMenuFrame = QFrame(self.topbar_menu)
        self.slideMenuFrame.setObjectName(u"slideMenuFrame")
        self.slideMenuFrame.setMinimumSize(QSize(156, 160))
        self.slideMenuFrame.setMaximumSize(QSize(1999, 1999))
        self.slideMenuFrame.setStyleSheet(u"background-color: black;")
        self.slideMenuFrame.setFrameShape(QFrame.StyledPanel)
        self.slideMenuFrame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_3 = QHBoxLayout(self.slideMenuFrame)
        self.horizontalLayout_3.setSpacing(5)
        self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
        self.horizontalLayout_3.setContentsMargins(9, 6, 6, 6)
        self.slideMenuButton = QPushButton(self.slideMenuFrame)
        self.slideMenuButton.setObjectName(u"slideMenuButton")
        self.slideMenuButton.setMinimumSize(QSize(153, 100))
        self.slideMenuButton.setMaximumSize(QSize(400, 500))
        self.slideMenuButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.slideMenuButton.setStyleSheet(
            u"QPushButton{\n"
            "	border-radius: 16px;\n"
            "}\n"
            "QPushButton:hover{\n"
            "	background-color: rgb(208, 116, 53);\n"
            "}\n"
            "\n"
            "")
        icon = QIcon()
        icon.addFile(u":/Icons/Icons/Menu.svg", QSize(), QIcon.Normal,
                     QIcon.Off)
        self.slideMenuButton.setIcon(icon)
        self.slideMenuButton.setIconSize(QSize(70, 70))

        self.horizontalLayout_3.addWidget(self.slideMenuButton)

        self.horizontalLayout_2.addWidget(self.slideMenuFrame, 0, Qt.AlignLeft)

        self.titlleFrame = QFrame(self.topbar_menu)
        self.titlleFrame.setObjectName(u"titlleFrame")
        self.titlleFrame.setStyleSheet(u"margin-left: 20%;")
        self.titlleFrame.setFrameShape(QFrame.StyledPanel)
        self.titlleFrame.setFrameShadow(QFrame.Raised)
        self.verticalLayout_4 = QVBoxLayout(self.titlleFrame)
        self.verticalLayout_4.setObjectName(u"verticalLayout_4")
        self.verticalLayout_4.setContentsMargins(0, 6, 0, -1)
        self.titleLabel = QLabel(self.titlleFrame)
        self.titleLabel.setObjectName(u"titleLabel")
        font = QFont()
        font.setFamily(u"Bahnschrift")
        font.setPointSize(24)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.titleLabel.setFont(font)
        self.titleLabel.setStyleSheet(u"color: #bd6e38;\n" "")
        self.titleLabel.setAlignment(Qt.AlignCenter)

        self.verticalLayout_4.addWidget(self.titleLabel)

        self.horizontalLayout_2.addWidget(self.titlleFrame)

        self.window_buttons = QFrame(self.topbar_menu)
        self.window_buttons.setObjectName(u"window_buttons")
        self.window_buttons.setStyleSheet(u"border: none;\n"
                                          "margin-right: 5%;\n"
                                          "")
        self.window_buttons.setFrameShape(QFrame.WinPanel)
        self.window_buttons.setFrameShadow(QFrame.Raised)
        self.horizontalLayout = QHBoxLayout(self.window_buttons)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.horizontalLayout.setContentsMargins(0, 0, 0, 9)
        self.minimazeButton = QPushButton(self.window_buttons)
        self.minimazeButton.setObjectName(u"minimazeButton")
        self.minimazeButton.setMinimumSize(QSize(90, 90))
        self.minimazeButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.minimazeButton.setStyleSheet(
            u"QPushButton:hover{\n"
            "	background-color: rgb(154, 154, 154);\n"
            "}")
        icon1 = QIcon()
        icon1.addFile(u":/Icons/Icons/Minimaze-Icon.svg", QSize(),
                      QIcon.Normal, QIcon.Off)
        self.minimazeButton.setIcon(icon1)
        self.minimazeButton.setIconSize(QSize(41, 41))

        self.horizontalLayout.addWidget(self.minimazeButton)

        self.maximazeButton = QPushButton(self.window_buttons)
        self.maximazeButton.setObjectName(u"maximazeButton")
        self.maximazeButton.setMinimumSize(QSize(95, 95))
        self.maximazeButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.maximazeButton.setStyleSheet(
            u"QPushButton:hover{\n"
            "	background-color: rgb(154, 154, 154);\n"
            "}")
        icon2 = QIcon()
        icon2.addFile(u":/Icons/Icons/MaximazeButton_2.svg", QSize(),
                      QIcon.Normal, QIcon.Off)
        self.maximazeButton.setIcon(icon2)
        self.maximazeButton.setIconSize(QSize(56, 56))

        self.horizontalLayout.addWidget(self.maximazeButton)

        self.closeButton = QPushButton(self.window_buttons)
        self.closeButton.setObjectName(u"closeButton")
        self.closeButton.setMinimumSize(QSize(100, 100))
        self.closeButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.closeButton.setStyleSheet(u"QPushButton:hover{\n"
                                       "	background-color: rgb(170, 0, 0);\n"
                                       "}")
        icon3 = QIcon()
        icon3.addFile(u":/Icons/Icons/WindowCloseButton.svg", QSize(),
                      QIcon.Normal, QIcon.Off)
        self.closeButton.setIcon(icon3)
        self.closeButton.setIconSize(QSize(52, 52))

        self.horizontalLayout.addWidget(self.closeButton)

        self.horizontalLayout_2.addWidget(self.window_buttons, 0,
                                          Qt.AlignRight | Qt.AlignVCenter)

        self.verticalLayout.addWidget(self.topbar_menu)

        self.gridLayout = QGridLayout()
        self.gridLayout.setSpacing(0)
        self.gridLayout.setObjectName(u"gridLayout")
        self.left_side_menu = QFrame(self.centralwidget)
        self.left_side_menu.setObjectName(u"left_side_menu")
        self.left_side_menu.setMinimumSize(QSize(170, 0))
        self.left_side_menu.setMaximumSize(QSize(170, 16777215))
        self.left_side_menu.setStyleSheet(u"QFrame{\n"
                                          "	background-color: black;\n"
                                          "}\n"
                                          "QPushButton{\n"
                                          "	background: transparent;\n"
                                          "	color: white;\n"
                                          "}")
        self.left_side_menu.setFrameShape(QFrame.WinPanel)
        self.left_side_menu.setFrameShadow(QFrame.Raised)
        self.verticalLayout_3 = QVBoxLayout(self.left_side_menu)
        self.verticalLayout_3.setSpacing(0)
        self.verticalLayout_3.setObjectName(u"verticalLayout_3")
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.left_menu_buttons = QFrame(self.left_side_menu)
        self.left_menu_buttons.setObjectName(u"left_menu_buttons")
        self.left_menu_buttons.setStyleSheet(u"margin-top: 10%;\n")
        self.left_menu_buttons.setFrameShape(QFrame.StyledPanel)
        self.left_menu_buttons.setFrameShadow(QFrame.Raised)
        self.verticalLayout_2 = QVBoxLayout(self.left_menu_buttons)
        self.verticalLayout_2.setSpacing(55)
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")
        self.verticalLayout_2.setContentsMargins(0, 28, 0, 20)
        self.homeButton = QPushButton(self.left_menu_buttons)
        self.homeButton.setObjectName(u"homeButton")
        self.homeButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.homeButton.setStyleSheet(u"margin-left: 0%;")
        icon4 = QIcon()
        icon4.addFile(u":/Icons/Icons/New-Home-Icon.svg", QSize(),
                      QIcon.Normal, QIcon.Off)
        self.homeButton.setIcon(icon4)
        self.homeButton.setIconSize(QSize(88, 88))

        self.verticalLayout_2.addWidget(self.homeButton)

        self.listButton = QPushButton(self.left_menu_buttons)
        self.listButton.setObjectName(u"listButton")
        self.listButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.listButton.setStyleSheet(u"margin-left: 0%;")
        icon5 = QIcon()
        icon5.addFile(u":/Icons/Icons/New-Search-Icon.svg", QSize(),
                      QIcon.Normal, QIcon.Off)
        self.listButton.setIcon(icon5)
        self.listButton.setIconSize(QSize(85, 85))

        self.verticalLayout_2.addWidget(self.listButton)

        self.addButton = QPushButton(self.left_menu_buttons)
        self.addButton.setObjectName(u"addButton")
        self.addButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.addButton.setStyleSheet(u"margin-left: 0%;")
        icon6 = QIcon()
        icon6.addFile(u":/Icons/Icons/New_Add.svg", QSize(), QIcon.Normal,
                      QIcon.Off)
        self.addButton.setIcon(icon6)
        self.addButton.setIconSize(QSize(85, 85))

        self.verticalLayout_2.addWidget(self.addButton)

        self.removeButton = QPushButton(self.left_menu_buttons)
        self.removeButton.setObjectName(u"removeButton")
        self.removeButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.removeButton.setStyleSheet(u"margin-left: 0%;")
        icon7 = QIcon()
        icon7.addFile(u":/Icons/Icons/New_Delete.svg", QSize(), QIcon.Normal,
                      QIcon.Off)
        self.removeButton.setIcon(icon7)
        self.removeButton.setIconSize(QSize(85, 85))

        self.verticalLayout_2.addWidget(self.removeButton)

        self.verticalLayout_3.addWidget(self.left_menu_buttons, 0,
                                        Qt.AlignHCenter | Qt.AlignTop)

        self.versionLabel = QLabel(self.left_side_menu)
        self.versionLabel.setMinimumSize(QSize(100, 100))
        self.versionLabel.setObjectName(u"versionLabel")
        self.versionLabel.setStyleSheet(u"color: white;\n"
                                        "margin-left: 10%;\n"
                                        "font-size: 30px;\n")

        self.verticalLayout_3.addWidget(self.versionLabel, 0,
                                        Qt.AlignHCenter | Qt.AlignBottom)

        self.gridLayout.addWidget(self.left_side_menu, 0, 0, 2, 1)

        self.footer = QFrame(self.centralwidget)
        self.footer.setObjectName(u"footer")
        self.footer.setMinimumSize(QSize(0, 40))
        self.footer.setMaximumSize(QSize(16777215, 40))
        self.footer.setStyleSheet(u"background-color: black;\n" "")
        self.footer.setFrameShape(QFrame.WinPanel)
        self.footer.setFrameShadow(QFrame.Raised)
        self.verticalLayout_10 = QVBoxLayout(self.footer)
        self.verticalLayout_10.setObjectName(u"verticalLayout_10")
        self.verticalLayout_10.setContentsMargins(0, 0, 0, 0)
        self.size_grip = QFrame(self.footer)
        self.size_grip.setObjectName(u"size_grip")
        self.size_grip.setMinimumSize(QSize(40, 30))
        self.size_grip.setFrameShape(QFrame.StyledPanel)
        self.size_grip.setFrameShadow(QFrame.Raised)

        self.verticalLayout_10.addWidget(self.size_grip, 0,
                                         Qt.AlignRight | Qt.AlignBottom)

        self.gridLayout.addWidget(self.footer, 1, 1, 1, 1)

        self.content_menu = QFrame(self.centralwidget)
        self.content_menu.setObjectName(u"content_menu")
        self.content_menu.setMinimumSize(QSize(30, 60))
        self.content_menu.setStyleSheet(u"background-color: #333;")
        self.content_menu.setFrameShape(QFrame.WinPanel)
        self.content_menu.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_4 = QHBoxLayout(self.content_menu)
        self.horizontalLayout_4.setSpacing(0)
        self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
        self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.containerPages = QStackedWidget(self.content_menu)
        self.containerPages.setObjectName(u"containerPages")
        font1 = QFont()
        font1.setFamily(u"Bahnschrift")
        font1.setPointSize(30)
        self.containerPages.setFont(font1)
        self.containerPages.setStyleSheet(u"background: #333;\n"
                                          "QcheckBox{\n"
                                          "	font: 12pt \"Bahnschript\";\n"
                                          "	font-style: italic;\n"
                                          "	color: white;\n"
                                          "}")
        self.HomeWWidget = QWidget()
        self.HomeWWidget.setObjectName(u"HomeWWidget")
        self.HomeWWidget.setStyleSheet(
            u"border-image: url(:/Icons/Icons/new_background.svg)")
        self.verticalLayout_11 = QVBoxLayout(self.HomeWWidget)
        self.verticalLayout_11.setObjectName(u"verticalLayout_11")
        self.verticalLayout_11.setContentsMargins(0, 0, 0, 0)
        self.homeTitleLabel = QLabel(self.HomeWWidget)
        self.homeTitleLabel.setObjectName(u"homeTitleLabel")
        font2 = QFont()
        font2.setFamily(u"Bahnschrift")
        font2.setPointSize(60)
        font2.setBold(True)
        font2.setWeight(75)
        self.homeTitleLabel.setFont(font2)
        self.homeTitleLabel.setStyleSheet(u"border-image: none;\n"
                                          "background: transparent;\n"
                                          "color: white;")
        self.homeTitleLabel.setAlignment(Qt.AlignCenter)

        self.verticalLayout_11.addWidget(self.homeTitleLabel)

        self.homeintroLabel = QLabel(self.HomeWWidget)
        self.homeintroLabel.setObjectName(u"homeintroLabel")
        font3 = QFont()
        font3.setFamily(u"Bahnschrift")
        font3.setPointSize(12)
        self.homeintroLabel.setFont(font3)
        self.homeintroLabel.setStyleSheet(u"border-image: none;\n"
                                          "background: transparent;\n"
                                          "color: white;\n")
        self.homeintroLabel.setAlignment(Qt.AlignCenter)

        self.verticalLayout_11.addWidget(self.homeintroLabel, 0,
                                         Qt.AlignHCenter | Qt.AlignTop)

        self.containerPages.addWidget(self.HomeWWidget)
        self.SearchWidget = QWidget()
        self.SearchWidget.setObjectName(u"SearchWidget")
        self.verticalLayout_9 = QVBoxLayout(self.SearchWidget)
        self.verticalLayout_9.setSpacing(7)
        self.verticalLayout_9.setObjectName(u"verticalLayout_9")
        self.verticalLayout_9.setContentsMargins(5, 0, 5, 5)
        self.searchbarFrame = QFrame(self.SearchWidget)
        self.searchbarFrame.setObjectName(u"searchbarFrame")
        self.searchbarFrame.setFrameShape(QFrame.StyledPanel)
        self.searchbarFrame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_8 = QHBoxLayout(self.searchbarFrame)
        self.horizontalLayout_8.setObjectName(u"horizontalLayout_8")
        self.searchbarLineEdit = QLineEdit(self.searchbarFrame)
        self.searchbarLineEdit.setObjectName(u"searchbarLineEdit")
        self.searchbarLineEdit.setStyleSheet(u"color: white;\n"
                                             "border: 1px solid white;\n"
                                             "border-radius: 30%;\n"
                                             "font-size: 45px;\n")
        self.searchbarLineEdit.setMinimumHeight(70)
        self.searchbarLineEdit.setPlaceholderText("Căutați aici...")
        self.searchbarLineEdit.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_8.addWidget(self.searchbarLineEdit)

        self.verticalLayout_9.addWidget(self.searchbarFrame)

        self.FilterCheckBoxFrame = QFrame(self.SearchWidget)
        self.FilterCheckBoxFrame.setObjectName(u"FilterCheckBoxFrame")
        self.FilterCheckBoxFrame.setStyleSheet(u"QRadioButton{\n"
                                               "	font: 9pt \"Bahnschript\";\n"
                                               "	font-style: italic;\n"
                                               "	color: white;\n"
                                               "}")
        self.FilterCheckBoxFrame.setFrameShape(QFrame.StyledPanel)
        self.FilterCheckBoxFrame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_9 = QHBoxLayout(self.FilterCheckBoxFrame)
        self.horizontalLayout_9.setObjectName(u"horizontalLayout_9")

        self.recentDateOrderRadioButton = QRadioButton(
            self.FilterCheckBoxFrame)
        self.recentDateOrderRadioButton.setObjectName(
            u"recentDateOrderRadioButton")

        self.horizontalLayout_9.addWidget(self.recentDateOrderRadioButton, 0,
                                          Qt.AlignHCenter)

        self.oldDateOrderRadioButton = QRadioButton(self.FilterCheckBoxFrame)
        self.oldDateOrderRadioButton.setObjectName(u"oldDateOrderRadioButton")

        self.horizontalLayout_9.addWidget(self.oldDateOrderRadioButton, 0,
                                          Qt.AlignHCenter)

        self.alphabeticalOrderRadioButton = QRadioButton(
            self.FilterCheckBoxFrame)
        self.alphabeticalOrderRadioButton.setObjectName(
            u"alphabeticalOrderRadioButton")

        self.horizontalLayout_9.addWidget(self.alphabeticalOrderRadioButton, 0,
                                          Qt.AlignHCenter)

        self.verticalLayout_9.addWidget(self.FilterCheckBoxFrame)

        self.tableFrame = QFrame(self.SearchWidget)
        self.tableFrame.setObjectName(u"tableFrame")
        self.tableFrame.setStyleSheet(u"border: 1px solid white;\n"
                                      "border-radius: 4px;\n"
                                      "margin-right:20%;\n"
                                      "margin-left:20%;\n")
        self.tableFrame.setFrameShape(QFrame.StyledPanel)
        self.tableFrame.setFrameShadow(QFrame.Raised)
        self.verticalLayout_12 = QVBoxLayout(self.tableFrame)
        self.verticalLayout_12.setSpacing(0)
        self.verticalLayout_12.setObjectName(u"verticalLayout_12")
        self.verticalLayout_12.setContentsMargins(0, 0, 0, 0)

        self.clientsDataTableView = QTableView(self.SearchWidget)

        data = pd.DataFrame(service.repository,
                            columns=['Nume', 'ID', 'Creat la', 'Expiră la'])
        self.model = TableModel(data)
        # filter proxy model
        self.filter_proxy_model = QSortFilterProxyModel()
        self.filter_proxy_model.setSourceModel(self.model)
        self.filter_proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.filter_proxy_model.setFilterKeyColumn(
            -1)  # -1 is for searching in all columns

        self.clientsDataTableView.setModel(self.filter_proxy_model)
        self.clientsDataTableView.verticalHeader().hide(
        )  # REMOVE VERTICAL HEADER
        self.clientsDataTableView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Interactive)
        self.clientsDataTableView.setHorizontalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.clientsDataTableView.horizontalHeader().setStretchLastSection(
            True)
        self.clientsDataTableView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.clientsDataTableView.setSelectionBehavior(QTableView.SelectRows)

        self.clientsDataTableView.setObjectName(u"clientsDataTableView")
        self.clientsDataTableView.setStyleSheet(u"border: none;\n"
                                                "margin-right:0%;\n"
                                                "margin-left:0%;\n"
                                                "font: 9pt 'Bahnschript';\n"
                                                "font-style: bold italic;\n")

        self.verticalLayout_12.addWidget(self.clientsDataTableView)

        self.verticalLayout_9.addWidget(self.tableFrame)

        self.ViewClientButton = QPushButton(self.SearchWidget)
        self.ViewClientButton.setObjectName(u"ViewClientButton")
        self.ViewClientButton.setMinimumSize(QSize(100, 50))
        self.ViewClientButton.setCursor(QCursor(Qt.PointingHandCursor))
        font4 = QFont()
        font4.setPointSize(15)
        self.ViewClientButton.setFont(font4)
        self.ViewClientButton.setStyleSheet(u"QPushButton{\n"
                                            "   background-color: #bd6e38;\n"
                                            "   color: white;\n"
                                            "   border: 4px solid white;\n"
                                            "   border-radius: 15px;\n"
                                            "   margin-bottom: 5%;\n"
                                            "}\n"
                                            "QPushButton:hover{\n"
                                            "   background-color: black;\n"
                                            "   border-color: #bd6e38;\n"
                                            "}\n")

        self.verticalLayout_9.addWidget(self.ViewClientButton, 0,
                                        Qt.AlignHCenter)

        self.containerPages.addWidget(self.SearchWidget)
        self.ViewClientWidget = QWidget()
        self.ViewClientWidget.setObjectName(u"ViewClientWidget")
        self.verticalLayout_13 = QVBoxLayout(self.ViewClientWidget)
        self.verticalLayout_13.setObjectName(u"verticalLayout_13")
        self.ClientViewFrame = QFrame(self.ViewClientWidget)
        self.ClientViewFrame.setObjectName(u"ClientViewFrame")
        self.ClientViewFrame.setStyleSheet(u"QLabel{\n"
                                           "	font: 12pt \"Bahnschript\";\n"
                                           "	font-style: italic;\n"
                                           "	color: white;\n"
                                           "}\n"
                                           "\n"
                                           "QLineEdit{\n"
                                           "	border-right: none;\n"
                                           "	border-top: none;\n"
                                           "	border-left: none;\n"
                                           "	border-bottom: 1px solid white;\n"
                                           "}")
        self.ClientViewFrame.setFrameShape(QFrame.StyledPanel)
        self.ClientViewFrame.setFrameShadow(QFrame.Raised)
        self.verticalLayout_14 = QVBoxLayout(self.ClientViewFrame)
        self.verticalLayout_14.setObjectName(u"verticalLayout_14")
        self.verticalLayout_14.setContentsMargins(-1, 15, 0, 0)
        self.gridLayout_4 = QGridLayout()
        self.gridLayout_4.setObjectName(u"gridLayout_4")
        self.gridLayout_4.setHorizontalSpacing(35)
        self.gridLayout_4.setVerticalSpacing(20)
        self.gridLayout_4.setContentsMargins(20, -1, 20, -1)
        self.NameLabel = QLabel(self.ClientViewFrame)
        self.NameLabel.setObjectName(u"NameLabel")

        self.gridLayout_4.addWidget(self.NameLabel, 0, 0, 1, 1)

        self.nameLineEdit = QLineEdit(self.ClientViewFrame)
        self.nameLineEdit.setObjectName(u"nameLineEdit")
        self.nameLineEdit.setStyleSheet(u"	font: 12pt \"Bahnschript\";\n"
                                        "	font-style: italic;\n"
                                        "	color: white;")
        self.nameLineEdit.setAlignment(Qt.AlignCenter)

        self.gridLayout_4.addWidget(self.nameLineEdit, 0, 1, 1, 1)

        self.CreationDateLabel = QLabel(self.ClientViewFrame)
        self.CreationDateLabel.setObjectName(u"CreationDateLabel")

        self.gridLayout_4.addWidget(self.CreationDateLabel, 0, 2, 1, 1)

        self.crationDateLineEdit = QLineEdit(self.ClientViewFrame)
        self.crationDateLineEdit.setObjectName(u"creationDateLineEdit")
        self.crationDateLineEdit.setStyleSheet(
            u"	font: 12pt \"Bahnschript\";\n"
            "	font-style: italic;\n"
            "	color: white;")
        self.crationDateLineEdit.setAlignment(Qt.AlignCenter)

        self.gridLayout_4.addWidget(self.crationDateLineEdit, 0, 3, 1, 1)

        self.IdLabel = QLabel(self.ClientViewFrame)
        self.IdLabel.setObjectName(u"IdLabel")

        self.gridLayout_4.addWidget(self.IdLabel, 1, 0, 1, 1)

        self.IdLineEdit = QLineEdit(self.ClientViewFrame)
        self.IdLineEdit.setObjectName(u"IdLineEdit")
        self.IdLineEdit.setStyleSheet(u"	font: 12pt \"Bahnschript\";\n"
                                      "	font-style: italic;\n"
                                      "	color: white;")
        self.IdLineEdit.setAlignment(Qt.AlignCenter)

        self.gridLayout_4.addWidget(self.IdLineEdit, 1, 1, 1, 1)

        self.ExpirationDateLabel = QLabel(self.ClientViewFrame)
        self.ExpirationDateLabel.setObjectName(u"ExpirationDateLabel")

        self.gridLayout_4.addWidget(self.ExpirationDateLabel, 1, 2, 1, 1)

        self.expirationDateLineEdit = QLineEdit(self.ClientViewFrame)
        self.expirationDateLineEdit.setObjectName(u"expirationDateLineEdit")
        self.expirationDateLineEdit.setStyleSheet(
            u"	font: 12pt \"Bahnschript\";\n"
            "	font-style: italic;\n"
            "	color: white;")
        self.expirationDateLineEdit.setAlignment(Qt.AlignCenter)

        self.gridLayout_4.addWidget(self.expirationDateLineEdit, 1, 3, 1, 1)

        self.verticalLayout_14.addLayout(self.gridLayout_4)

        self.Valid_InvalidLabel = QLabel(self.ClientViewFrame)
        self.Valid_InvalidLabel.setObjectName(u"Valid_InvalidLabel")
        font5 = QFont()
        font5.setFamily(u"Bahnschript")
        font5.setPointSize(25)
        font5.setBold(False)
        font5.setItalic(True)
        font5.setWeight(50)
        self.Valid_InvalidLabel.setFont(font5)
        self.Valid_InvalidLabel.setStyleSheet(u"font: 25pt \"Bahnschript\";\n"
                                              "font-style: italic;\n"
                                              "color: white;")
        self.Valid_InvalidLabel.setAlignment(Qt.AlignCenter)

        self.verticalLayout_14.addWidget(self.Valid_InvalidLabel)

        self.PrintButton = QPushButton(self.ClientViewFrame)
        self.PrintButton.setObjectName(u"PrintButton")
        self.PrintButton.setMinimumSize(QSize(180, 130))
        self.PrintButton.setCursor(QCursor(Qt.PointingHandCursor))
        font6 = QFont()
        font6.setPointSize(11)
        font6.setBold(True)
        font6.setWeight(75)
        self.PrintButton.setFont(font6)
        self.PrintButton.setStyleSheet(u"QPushButton{\n"
                                       "background-color: #bd6e38;\n"
                                       "color: white;\n"
                                       "border: 4px solid white;\n"
                                       "border-radius: 30%;\n"
                                       "margin-bottom: 40%;\n"
                                       "}\n"
                                       "QPushButton:hover{\n"
                                       "   background-color: black;\n"
                                       "   border-color: #bd6e38;\n"
                                       "}\n")

        self.verticalLayout_14.addWidget(self.PrintButton, 0, Qt.AlignHCenter)

        self.verticalLayout_13.addWidget(self.ClientViewFrame)

        self.containerPages.addWidget(self.ViewClientWidget)
        self.AddWidget = QWidget()
        self.AddWidget.setObjectName(u"AddWidget")
        self.verticalLayout_6 = QVBoxLayout(self.AddWidget)
        self.verticalLayout_6.setObjectName(u"verticalLayout_6")
        self.addTextFrame = QFrame(self.AddWidget)
        self.addTextFrame.setObjectName(u"addTextFrame")
        self.addTextFrame.setStyleSheet(u"border-bottom: 1px solid #bd6e38;\n"
                                        "border-top: 2px solid #bd6e38;")
        self.addTextFrame.setFrameShape(QFrame.StyledPanel)
        self.addTextFrame.setFrameShadow(QFrame.Raised)
        self.verticalLayout_5 = QVBoxLayout(self.addTextFrame)
        self.verticalLayout_5.setObjectName(u"verticalLayout_5")
        self.verticalLayout_5.setContentsMargins(0, -1, 0, -1)
        self.addTextLabel = QLabel(self.addTextFrame)
        self.addTextLabel.setObjectName(u"addTextLabel")
        font7 = QFont()
        font7.setFamily(u"Bahnschrift")
        font7.setPointSize(15)
        font7.setItalic(True)
        self.addTextLabel.setFont(font7)
        self.addTextLabel.setStyleSheet(u"color: white;\n" "border: none;")
        self.addTextLabel.setAlignment(Qt.AlignCenter)

        self.verticalLayout_5.addWidget(self.addTextLabel)

        self.verticalLayout_6.addWidget(self.addTextFrame)

        self.InsertNameFrame = QFrame(self.AddWidget)
        self.InsertNameFrame.setObjectName(u"InsertNameFrame")
        self.InsertNameFrame.setFrameShape(QFrame.StyledPanel)
        self.InsertNameFrame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_5 = QHBoxLayout(self.InsertNameFrame)
        self.horizontalLayout_5.setSpacing(13)
        self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
        self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.addNameLabel = QLabel(self.InsertNameFrame)
        self.addNameLabel.setObjectName(u"addNameLabel")
        font8 = QFont()
        font8.setFamily(u"Bahnschrift")
        font8.setPointSize(17)
        font8.setItalic(True)
        self.addNameLabel.setFont(font8)
        self.addNameLabel.setStyleSheet(u"color: white;\n"
                                        "margin-left:  70%;\n"
                                        "margin-bottom: 10%;\n"
                                        "")
        self.addNameLabel.setAlignment(Qt.AlignCenter)
        self.addNameLabel.setMargin(0)

        self.horizontalLayout_5.addWidget(self.addNameLabel)

        self.addLineEdit = QLineEdit(self.InsertNameFrame)
        self.addLineEdit.setObjectName(u"addLineEdit")
        self.addLineEdit.setMinimumSize(QSize(50, 0))
        font9 = QFont()
        font9.setFamily(u"Bahnschrift")
        font9.setPointSize(17)
        self.addLineEdit.setFont(font9)
        self.addLineEdit.setStyleSheet(u"margin-right: 70%;\n"
                                       "color: white;\n"
                                       "border-top: none;\n"
                                       "border-left: none;\n"
                                       "border-right: none;\n"
                                       "border-bottom: 1px solid white;\n"
                                       "\n"
                                       "")
        self.addLineEdit.setAlignment(Qt.AlignCenter)
        self.addLineEdit.setDragEnabled(False)

        self.horizontalLayout_5.addWidget(self.addLineEdit)

        self.verticalLayout_6.addWidget(self.InsertNameFrame)

        self.addButtonsFrame = QFrame(self.AddWidget)
        self.addButtonsFrame.setObjectName(u"addButtonsFrame")
        self.addButtonsFrame.setFrameShape(QFrame.StyledPanel)
        self.addButtonsFrame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_6 = QHBoxLayout(self.addButtonsFrame)
        self.horizontalLayout_6.setSpacing(40)
        self.horizontalLayout_6.setObjectName(u"horizontalLayout_6")
        self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.addPushBUtton = QPushButton(self.addButtonsFrame)
        self.addPushBUtton.setObjectName(u"addPushBUtton")
        self.addPushBUtton.setCursor(QCursor(Qt.PointingHandCursor))
        self.addPushBUtton.setMinimumSize(QSize(0, 30))
        font10 = QFont()
        font10.setFamily(u"Bahnschrift")
        font10.setPointSize(14)
        self.addPushBUtton.setFont(font10)
        self.addPushBUtton.setStyleSheet(u"QPushButton{\n"
                                         "  background-color: #bd6e38;\n"
                                         "  color: white;\n"
                                         "  border: 4px solid white;\n"
                                         "  border-radius: 15px;\n"
                                         "  margin-left: 70%;\n"
                                         "  margin-right: 50%;\n"
                                         "}\n"
                                         "QPushButton:hover{\n"
                                         "      background-color: black;\n"
                                         "      border-color: #bd6e38;\n "
                                         "}\n")

        self.horizontalLayout_6.addWidget(self.addPushBUtton)

        self.quitPushButton = QPushButton(self.addButtonsFrame)
        self.quitPushButton.setObjectName(u"quitPushButton")
        self.quitPushButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.quitPushButton.setMinimumSize(QSize(0, 34))
        self.quitPushButton.setFont(font10)
        self.quitPushButton.setStyleSheet(u"QPushButton{\n"
                                          "  background-color: #bd6e38;\n"
                                          "  color: white;\n"
                                          "  border: 4px solid white;\n"
                                          "  border-radius: 15px;\n"
                                          "  margin-left: 70%;\n"
                                          "  margin-right: 50%;\n"
                                          "}\n"
                                          "QPushButton:hover{\n"
                                          "   background-color: black;\n"
                                          "   border-color: #bd6e38;\n "
                                          "}\n")

        self.horizontalLayout_6.addWidget(self.quitPushButton)

        self.verticalLayout_6.addWidget(self.addButtonsFrame)

        self.containerPages.addWidget(self.AddWidget)
        self.RemoveWidget = QWidget()
        self.RemoveWidget.setObjectName(u"RemoveWidget")
        self.horizontalLayout_11 = QHBoxLayout(self.RemoveWidget)
        self.horizontalLayout_11.setSpacing(2)
        self.horizontalLayout_11.setObjectName(u"horizontalLayout_11")
        self.horizontalLayout_11.setContentsMargins(0, 2, 2, 3)
        self.removeElementsFrame = QFrame(self.RemoveWidget)
        self.removeElementsFrame.setObjectName(u"removeElementsFrame")
        self.verticalLayout_16 = QVBoxLayout(self.removeElementsFrame)
        self.verticalLayout_16.setSpacing(0)
        self.verticalLayout_16.setObjectName(u"verticalLayout_16")
        self.verticalLayout_16.setContentsMargins(0, -1, -1, -1)
        self.verticalLayout_15 = QVBoxLayout()
        self.verticalLayout_15.setObjectName(u"verticalLayout_15")
        self.removeTextFrame = QFrame(self.removeElementsFrame)
        self.removeTextFrame.setObjectName(u"removeTextFrame")
        self.removeTextFrame.setStyleSheet(
            u"border-right: 4px solid #bd6e38;\n"
            "border-bottom: 4px solid #bd6e38;\n"
            "border: 4px solid #bd6e38;\n"
            "border-top-right-radius: 5%;\n"
            "border-bottom-right-radius: 5%;\n"
            "border-left: none;\n")
        self.removeTextFrame.setFrameShape(QFrame.StyledPanel)
        self.removeTextFrame.setFrameShadow(QFrame.Raised)
        self.verticalLayout_7 = QVBoxLayout(self.removeTextFrame)
        self.verticalLayout_7.setObjectName(u"verticalLayout_7")
        self.verticalLayout_7.setContentsMargins(0, -1, 0, -1)
        self.removeLabel = QLabel(self.removeTextFrame)
        self.removeLabel.setObjectName(u"removeLabel")
        self.removeLabel.setFont(font7)
        self.removeLabel.setStyleSheet(u"color: white;\n" "border: none;")
        self.removeLabel.setAlignment(Qt.AlignCenter)

        self.verticalLayout_7.addWidget(self.removeLabel)

        self.verticalLayout_15.addWidget(self.removeTextFrame, 0,
                                         Qt.AlignLeft | Qt.AlignTop)

        self.removeSearchbarFrame = QFrame(self.removeElementsFrame)
        self.removeSearchbarFrame.setObjectName(u"removeSearchbarFrame")
        self.removeSearchbarFrame.setStyleSheet(u"")
        self.removeSearchbarFrame.setFrameShape(QFrame.StyledPanel)
        self.removeSearchbarFrame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_10 = QHBoxLayout(self.removeSearchbarFrame)
        self.horizontalLayout_10.setObjectName(u"horizontalLayout_10")
        self.removeSearchbarLineEdit = QLineEdit(self.removeSearchbarFrame)
        self.removeSearchbarLineEdit.setObjectName(u"removeSearchbarLineEdit")
        self.removeSearchbarLineEdit.setStyleSheet(
            u"color: white;\n"
            "border: 1px solid white;\n"
            "border-radius: 30%;\n"
            "font: 15pt 'BahnSchrift'\n")
        self.removeSearchbarLineEdit.setPlaceholderText("Căutați aici...")
        self.removeSearchbarLineEdit.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_10.addWidget(self.removeSearchbarLineEdit)

        self.verticalLayout_15.addWidget(self.removeSearchbarFrame, 0,
                                         Qt.AlignTop)

        self.verticalLayout_16.addLayout(self.verticalLayout_15)

        self.removeButtonsFrame = QFrame(self.removeElementsFrame)
        self.removeButtonsFrame.setObjectName(u"removeButtonsFrame")
        self.removeButtonsFrame.setFrameShape(QFrame.StyledPanel)
        self.removeButtonsFrame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_7 = QHBoxLayout(self.removeButtonsFrame)
        self.horizontalLayout_7.setSpacing(40)
        self.horizontalLayout_7.setObjectName(u"horizontalLayout_7")
        self.horizontalLayout_7.setContentsMargins(0, 0, 0, 0)
        self.removePushButton = QPushButton(self.removeButtonsFrame)
        self.removePushButton.setObjectName(u"removePushButton")
        self.removePushButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.removePushButton.setMinimumSize(QSize(0, 34))
        self.removePushButton.setFont(font10)
        self.removePushButton.setStyleSheet(u"QPushButton{\n"
                                            "   background-color: #bd6e38;\n"
                                            "   color: white;\n"
                                            "   border: 4px solid white;\n"
                                            "   border-radius: 15px;\n"
                                            "   margin-right: 20%;\n"
                                            "   margin-left:40%;\n"
                                            "}\n"
                                            "QPushButton:hover{\n"
                                            "   background-color: black;\n"
                                            "   border-color: #bd6e38;\n"
                                            "}\n")

        self.horizontalLayout_7.addWidget(self.removePushButton)

        self.quitPushButton_2 = QPushButton(self.removeButtonsFrame)
        self.quitPushButton_2.setObjectName(u"quitPushButton_2")
        self.quitPushButton_2.setCursor(QCursor(Qt.PointingHandCursor))
        self.quitPushButton_2.setMinimumSize(QSize(0, 34))
        self.quitPushButton_2.setFont(font10)
        self.quitPushButton_2.setStyleSheet(u"QPushButton{\n"
                                            "   background-color: #bd6e38;\n"
                                            "   color: white;\n"
                                            "   border: 4px solid white;\n"
                                            "   border-radius: 15px;\n"
                                            "   margin-right: 20%;\n"
                                            "   margin-left: 20%;\n"
                                            "}\n"
                                            "QPushButton:hover{\n"
                                            "   background-color: black;\n"
                                            "   border-color: #bd6e38;\n"
                                            "}\n")

        self.horizontalLayout_7.addWidget(self.quitPushButton_2)

        self.verticalLayout_16.addWidget(self.removeButtonsFrame, 0,
                                         Qt.AlignBottom)

        self.horizontalLayout_11.addWidget(self.removeElementsFrame, 0,
                                           Qt.AlignLeft)

        self.removeTableFrame = QFrame(self.RemoveWidget)
        self.removeTableFrame.setObjectName(u"removeTableFrame")
        self.removeTableFrame.setStyleSheet(u"border: 1px solid white;\n"
                                            "border-radius: 4px;\n")
        self.removeTableFrame.setFrameShape(QFrame.StyledPanel)
        self.removeTableFrame.setFrameShadow(QFrame.Raised)
        self.verticalLayout_8 = QVBoxLayout(self.removeTableFrame)
        self.verticalLayout_8.setObjectName(u"verticalLayout_8")
        self.verticalLayout_8.setContentsMargins(0, 0, 0, 0)
        self.removetableView = QTableView(self.removeTableFrame)

        self.remove_model = TableModel(data)

        self.remove_filter_proxy_model = QSortFilterProxyModel()
        self.remove_filter_proxy_model.setSourceModel(self.remove_model)
        self.remove_filter_proxy_model.setFilterCaseSensitivity(
            Qt.CaseInsensitive)
        self.remove_filter_proxy_model.setFilterKeyColumn(-1)

        self.removetableView.setModel(self.remove_filter_proxy_model)
        self.removetableView.verticalHeader().hide()  # REMOVE VERTICAL HEADER
        self.removetableView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Interactive)
        self.removetableView.setHorizontalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.removetableView.horizontalHeader().setStretchLastSection(True)
        self.removetableView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.removetableView.setSelectionBehavior(QTableView.SelectRows)

        self.removetableView.setObjectName(u"removetableView")
        self.removetableView.setStyleSheet(u"border: none;\n"
                                           "margin-right:0%;\n"
                                           "margin-left:0%;\n"
                                           "font: 9pt 'Bahnschript';\n"
                                           "font-style: bold italic;\n")

        self.verticalLayout_8.addWidget(self.removetableView)

        self.horizontalLayout_11.addWidget(self.removeTableFrame)

        self.containerPages.addWidget(self.RemoveWidget)

        self.horizontalLayout_4.addWidget(self.containerPages)

        self.gridLayout.addWidget(self.content_menu, 0, 1, 1, 1)

        self.verticalLayout.addLayout(self.gridLayout)

        Main.setCentralWidget(self.centralwidget)

        self.retranslateUi(Main)

        self.containerPages.setCurrentIndex(0)

        QMetaObject.connectSlotsByName(Main)

    # setupUi

    def retranslateUi(self, Main):
        Main.setWindowTitle(
            QCoreApplication.translate("Main", u"MainWindow", None))
        self.slideMenuButton.setText("")
        self.titleLabel.setText(
            QCoreApplication.translate(
                "Main",
                u"<html><head/><body><p>STIHL SERVER</p></body></html>", None))
        self.minimazeButton.setText("")
        self.maximazeButton.setText("")
        self.closeButton.setText("")

        self.versionLabel.setText(
            QCoreApplication.translate("Main", u"v 1.2", None))
        self.homeTitleLabel.setText(
            QCoreApplication.translate("Main", u"HOME", None))
        self.homeintroLabel.setText(
            QCoreApplication.translate(
                "Main",
                u"<html><head/><body><p><span style=\"background-color:#333;\">Aceasta este aplica\u021bia pentru gestionarea clien\u021bilor.</span></p><p><span style=\"background-color:#333;\">Pentru a vizuliza un client da-\u021bi click pe iconi\u021ba cu lup\u0103.</span></p><p><span style=\"background-color:#333;\">Pentru a filtra datele bifa\u021bi, \u00een func\u021bie de preferin\u021b\u0103, c\u0103su\u021bele de sub bara de c\u0103utare.</span></p><p><span style=\"background-color:#333;\">Pentru a genera un pdf voucher selecta\u021bi clientul dorit, da\u021bi click pe butonul &quot;Vizualizeaz\u0103&quot;</span></p><p><span style=\"background-color:#333;\">dup\u0103 care, ap\u0103sa\u021bi &quot;Printare client&quot;.</span></p><p><span style=\"background-color:#333;\">Pentru a ad\u0103uga/\u0219terge un client ap\u0103sa\u021bi pe iconi\u021ba cu plus, respectiv &quot;x&quot;.</span></p></body></html>",
                None))

        self.recentDateOrderRadioButton.setText(
            QCoreApplication.translate("Main", u"Dat\u0103 recent\u0103",
                                       None))
        self.oldDateOrderRadioButton.setText(
            QCoreApplication.translate("Main", u"Dat\u0103 vehce", None))
        self.alphabeticalOrderRadioButton.setText(
            QCoreApplication.translate("Main", u"Ordonare alfabetic\u0103",
                                       None))
        self.ViewClientButton.setText(
            QCoreApplication.translate("Main", u" Vizualizeaz\u0103 ", None))
        self.NameLabel.setText(
            QCoreApplication.translate("Main", u"Nume:", None))
        self.CreationDateLabel.setText(
            QCoreApplication.translate("Main", u"Dat\u0103 creare: ", None))
        self.IdLabel.setText(QCoreApplication.translate("Main", u"ID:", None))
        self.ExpirationDateLabel.setText(
            QCoreApplication.translate("Main", u"Dat\u0103 expirare: ", None))
        self.Valid_InvalidLabel.setText(
            QCoreApplication.translate("Main", u"Client valid", None))
        self.PrintButton.setText(
            QCoreApplication.translate("Main", u"  Genereaz\u0103 PDF ", None))
        self.addTextLabel.setText(
            QCoreApplication.translate(
                "Main",
                u"<html><head/><body><p align=\"center\">Pentru a ad\u0103uga un client nou trebuie </p><p align=\"center\">s\u0103 introduce\u021bi numele:</p></body></html>",
                None))
        self.addNameLabel.setText(
            QCoreApplication.translate("Main", u"Nume: ", None))
        self.addPushBUtton.setText(
            QCoreApplication.translate("Main", u"Adaug\u0103", None))
        self.quitPushButton.setText(
            QCoreApplication.translate("Main", u"Renun\u021b\u0103", None))
        self.removeLabel.setText(
            QCoreApplication.translate(
                "Main",
                u"<html><head/><body><p align=\"center\">Pentru a \u0219terge un client trebuie s\u0103 </p><p align=\"center\">selecta\u021bi r\u00e2ndul corespunz\u0103tor</p></body></html>",
                None))
        self.removePushButton.setText(
            QCoreApplication.translate("Main", u"\u0218terge", None))
        self.quitPushButton_2.setText(
            QCoreApplication.translate("Main", u"Renun\u021b\u0103", None))
Ejemplo n.º 7
0
    def setup_p_view(self) -> None:
        """inits stacked widget page widget

        Returns:
            None"""
        self.p_view = QtWidgets.QWidget()
        self.stacked_widget.addWidget(self.p_view)

        self.model = QStandardItemModel(self.p_view)
        self.model.setHorizontalHeaderLabels(labels)

        self.filters = []
        source_model = self.model
        for filter_num in range(7):
            filter = QSortFilterProxyModel()
            filter.setSourceModel(source_model)
            filter.setFilterKeyColumn(filter_num)
            source_model = filter
            self.filters.append(filter)

        delegate = ComboDelegate()
        self.table = QtWidgets.QTableView(self.p_view)
        self.table.setModel(self.filters[-1])
        self.table.setItemDelegateForColumn(2, delegate)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.header = FilterHeader(self.table)
        self.header.set_filter_boxes()
        self.header.setMaximumHeight(50)
        self.table.setHorizontalHeader(self.header)

        self.bt_burger = QPushButton(self.p_view)
        self.bt_burger.setIcon(QIcon("./data/menu2.svg"))
        self.bt_burger.setIconSize(QSize(30, 30))
        self.bt_burger.setToolTip('slide out description')
        l_burger = QLabel("menu", self.p_view)

        self.bt_register_new = QPushButton(self.p_view)
        self.bt_register_new.setIcon(QIcon("./data/add.ico"))
        self.bt_register_new.setIconSize(QSize(30, 30))
        self.bt_register_new.setToolTip("register new")
        l_register_new = QLabel("register new", self.p_view)

        self.bt_delete_column = QPushButton(self.p_view)
        self.bt_delete_column.setIcon(QIcon("./data/remove.ico"))
        self.bt_delete_column.setIconSize(QSize(30, 30))
        self.bt_delete_column.setToolTip(
            "delete columns with min 1 cell selected")
        l_delete = QLabel("delete column", self.p_view)

        self.bt_hide_show_filter = QPushButton(self.p_view)
        self.bt_hide_show_filter.setIcon(QIcon("./data/show_hide.ico"))
        self.bt_hide_show_filter.setIconSize(QSize(30, 30))
        self.bt_hide_show_filter.setToolTip("hide/show filter input")
        l_hide_show = QLabel("hide/show", self.p_view)

        self.left_btn_frame = QFrame(self.p_view)
        self.left_btn_frame.setMaximumWidth(40)
        self.left_btn_frame.setContentsMargins(0, 0, 0, 0)

        self.left_menu_frame = QFrame(self.p_view)
        self.left_menu_frame.setMaximumWidth(0)
        self.left_menu_frame.setContentsMargins(0, 0, 0, 0)

        p_view_layout2 = QtWidgets.QVBoxLayout(self.left_btn_frame)
        p_view_layout2.addWidget(self.bt_burger)
        p_view_layout2.addWidget(self.bt_register_new)
        p_view_layout2.addWidget(self.bt_delete_column)
        p_view_layout2.addWidget(self.bt_hide_show_filter)
        p_view_layout2.setAlignment(Qt.AlignTop)
        p_view_layout2.setContentsMargins(0, 0, 0, 0)

        self.p_view_layout3 = QtWidgets.QVBoxLayout(self.left_menu_frame)
        self.p_view_layout3.addWidget(l_burger)
        self.p_view_layout3.addWidget(l_register_new)
        self.p_view_layout3.addWidget(l_delete)
        self.p_view_layout3.addWidget(l_hide_show)
        self.p_view_layout3.setAlignment(Qt.AlignTop | Qt.AlignCenter)
        self.p_view_layout3.setContentsMargins(0, 0, 0, 0)
        self.p_view_layout3.setSpacing(25)

        p_view_layout = QHBoxLayout(self.p_view)
        p_view_layout.setContentsMargins(0, 0, 0, 0)
        p_view_layout.addWidget(self.left_btn_frame)
        p_view_layout.addWidget(self.left_menu_frame)
        p_view_layout.addWidget(self.table)
        self.p_view.setLayout(p_view_layout)

        self.p_view.addAction(self.action_open)
        self.p_view.addAction(self.action_save)
        self.p_view.addAction(self.action_new)
        self.p_view.addAction(self.action_print)
        self.p_view.addAction(self.action_register)
        self.p_view.addAction(self.action_hide_menu_bar)
Ejemplo n.º 8
0
class TreeCard(QDialog):
    def __init__(self, db=0, mode=0):
        super().__init__()

        layout = QGridLayout()
        #self.central_widget.setLayout(layout)
        self.resize(800, self.height())
        self.lb_find = QInvisibleButton('Поиск')
        self.lb_find.setFont(mainfont)
        self.te_find = QLineEdit()
        self.te_find.setFont(mainfont)
        self.pid = 0

        layout.addWidget(self.te_find, 0, 0, 1, 1)
        layout.addWidget(self.lb_find, 0, 0, 1, 1)
        #if mode:
        #   te.setReadOnly(False)
        self.lb_find.clicked.connect(self.button_pressed)
        self.te_find.returnPressed.connect(self.line_edit_return_pressed)

        self.database = db

        self.table = QTableView()  # Создаём таблицу
        self.table.doubleClicked.connect(self.viewPerson)
        #self.table = table

        self.model = TableModel(self.database.get_peoples())
        self.table.setModel(self.model)
        self.table.resizeRowsToContents()
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        #self.table.setSelectionMode(QAbstractItemView.SingleSelection);
        self.model.dataChanged.connect(self.table.update)

        layout.addWidget(self.table)
        self.setLayout(layout)

    def viewPerson(self):
        select = self.table.selectionModel()
        pid_list = [
            index.data()
            for index in self.table.selectionModel().selection().indexes()
            if index.column() == 0
        ]
        if len(pid_list) == 1:
            self.pid = int(pid_list[0])
            print(int(pid_list[0]))
            self.accept()
        return 0

    def button_pressed(self):
        #sender = self.sender()
        self.lb_find.stackUnder(self.te_find)
        self.te_find.setFocus()

    def line_edit_return_pressed(self):
        print(self.te_find.text())

        self.model = TableModel(self.database.get_peoples())

        self.proxy_model = QSortFilterProxyModel(self.model)
        self.proxy_model.setSourceModel(self.model)
        self.proxy_model.setFilterFixedString(self.te_find.text())
        self.proxy_model.setFilterKeyColumn(-1)
        #print(self.proxy_model.filterKeyColumn())

        self.table.setModel(self.proxy_model)
        self.table.update()
        self.table.resizeRowsToContents()

        #sender = self.sender()
        self.te_find.stackUnder(self.lb_find)
        self.lb_find.setFocus()
Ejemplo n.º 9
0
    class __HPasteCollectionWidget(CollectionWidget):
        def __init__(self, parent=None):
            super(HPasteCollectionWidget.__HPasteCollectionWidget,
                  self).__init__(parent,
                                 metadataExposedKeys=('raw_url', 'nettype'))
            for x in xrange(1, 5):
                self.ui.mainView.horizontalHeader().hideSection(x)

            self.__nepane = None
            self.__netType = ''

            self.__nettypeFilter = QSortFilterProxyModel(self)
            self.__nettypeFilter.setFilterKeyColumn(4)
            self.__nettypeFilter.setFilterRegExp(
                QRegExp("*", Qt.CaseInsensitive, QRegExp.Wildcard))
            self.appendFilter(self.__nettypeFilter)

            self.accepted.connect(self.doOnAccept)

            self.__insideAuthCallback = False
            #self.setProperty("houdiniStyle", True)
            ss = "QTableView{border : 0px solid; gridline-color: rgb(48,48,48)}"
            ss += "QHeaderView::section{border-style: none; border-bottom: 0px; border-right: 0px;}"
            self.setStyleSheet(ss)

            self.__savedNetworkViewPos = None

        def setNetworkEditor(self, pane):
            if (not isinstance(pane, hou.NetworkEditor)):
                pane = None

            self.__nepane = pane  #save to position pasted nodes in it
            self.__savedNetworkViewPos = pane.cursorPosition()

            if (pane is None):
                nettype = '*'
                self.__netType = ''  #Used to create new snippet types
            else:
                nettype = hpaste.getChildContext(pane.pwd(),
                                                 hou.applicationVersion())
                self.__netType = nettype
            self.__nettypeFilter.setFilterRegExp(
                QRegExp(nettype, Qt.CaseInsensitive, QRegExp.Wildcard))

        @Slot(object)
        def doOnAccept(self, item):
            if (item is None): return
            try:
                try:  #>h16
                    hou.clearAllSelected()
                except:  #<=h15.5
                    hou.node("/obj").setSelected(False,
                                                 clear_all_selected=True)
                hpaste.stringToNodes(
                    item.content(),
                    ne=self.__nepane,
                    override_network_position=self.__savedNetworkViewPos)
            except RuntimeWarning as e:
                log('Warnings encountered during load:\n%s' % e.message, 2)
            except Exception as e:
                hou.ui.displayMessage("could not paste: %s" % e.message,
                                      severity=hou.severityType.Warning)

        def _addItem(self, collection):
            #Please, dont throw from here!
            try:
                nodes = hou.selectedItems()
            except:
                nodes = hou.selectedNodes()
            if (len(nodes) == 0):
                QMessageBox.warning(self, 'not created',
                                    'selection is empty, nothing to add')
                return

            while True:
                #btn,(name,desc) = (0,('1','2'))#hou.ui.readMultiInput('enter some information about new item',('name','description'),buttons=('Ok','Cancel'))
                name, desc, public, good = QDoubleInputDialog.getDoubleTextCheckbox(
                    self, 'adding a new item to %s' % collection.name(),
                    'enter new item details', 'name', 'description', 'public',
                    '', 'a snippet', False)
                if (not good): return

                if (len(name) > 0):
                    break
                    #validity check

            try:
                #print(name)
                #print(desc)
                #print(hpaste.nodesToString(nodes))
                self.model().addItemToCollection(
                    collection,
                    name,
                    desc,
                    hpaste.nodesToString(nodes),
                    public,
                    metadata={'nettype': self.__netType})
            except CollectionSyncError as e:
                QMessageBox.critical(self, 'something went wrong!',
                                     'Server error occured: %s' % e.message)

        def _changeAccess(self, index):
            item = index.internalPointer()
            text, good = QInputDialog.getItem(
                None,
                'modify item access',
                'choose new access type:', ['private', 'public'],
                current=item.access() == CollectionItem.AccessType.public,
                editable=False)
            if (not good): return
            newaccess = CollectionItem.AccessType.public if text == 'public' else CollectionItem.AccessType.private
            if (newaccess == item.access()): return
            item.setAccess(newaccess)

        def _replaceContent(self, index):
            try:
                nodes = hou.selectedItems()
            except:
                nodes = hou.selectedNodes()
            if (len(nodes) == 0):
                QMessageBox.warning(self, 'cannot replace',
                                    'selection is empty')
                return
            item = index.internalPointer()
            good = QMessageBox.warning(
                self, 'sure?',
                'confirm that you want to replace the content of selected item "%s". This operation can not be undone.'
                % item.name(),
                QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok
            if (not good): return
            try:
                item.setContent(hpaste.nodesToString(nodes))
            except CollectionSyncError as e:
                QMessageBox.critical(self, 'something went wrong!',
                                     'Server error occured: %s' % e.message)

        def _itemInfo(self, index):
            item = index.internalPointer()
            accesstext = 'public' if item.access(
            ) == CollectionItem.AccessType.public else 'private'
            readonlytext = 'readonly' if item.readonly() else 'editable'
            info = 'name: %s\n%s\naccess: %s\n%s\n\ncollection id: %s\n\nmetadata:\n' % (
                item.name(), item.description(), accesstext, readonlytext,
                item.id())
            info += '\n'.join(('%s : %s' % (key, item.metadata()[key])
                               for key in item.metadata()))

            QMessageBox.information(self, 'item information', info)

        def _renameItem(self, index):
            item = index.internalPointer()
            oldname = item.name()
            olddesc = item.description()
            newname, newdesc, good = QDoubleInputDialog.getDoubleText(
                self, 'modify item info',
                'Enter new item name and description', 'name', 'description',
                oldname, olddesc)
            if (not good): return
            if (newname != oldname): item.setName(newname)
            if (newdesc != olddesc): item.setDescription(newdesc)

        def _removeIcon(self, index):
            ok = QMessageBox.warning(
                self, 'sure?',
                'confirm removing Icon. This operation can not be undone.',
                QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok
            if ok:
                super(HPasteCollectionWidget.__HPasteCollectionWidget,
                      self)._removeIcon(index)

        def _confirmRemove(self, index):
            return QMessageBox.warning(
                self, 'sure?',
                'confirm removing the item from collection. This operation can not be undone.',
                QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok

        # a callback for authoriser
        def _authCallback(self, callbackinfo):
            auth, public, action = callbackinfo

            if self.__insideAuthCallback: return  # prevent looping
            self.__insideAuthCallback = True

            try:
                if action == 0 or (action == 2 and not auth['enabled']):
                    good = self.removeCollection(auth['user'])
                    if not good:  # means something went wrong during  removal attempt - probably async collection syncing problem. Try later
                        if public:
                            GithubAuthorizator.setPublicCollsctionEnabled(
                                auth['user'], True)
                        else:
                            GithubAuthorizator.setAuthorizationEnabled(
                                auth['user'], True)

                elif action == 1 or (action == 2 and auth['enabled']):
                    if public:
                        self.addCollection(
                            GithubCollection(auth['user'], public=True),
                            async=True
                        )  # TODO: reuse some token for public access
                    else:
                        self.addCollection(GithubCollection(auth['token']),
                                           async=True)
            except CollectionSyncError as e:
                QMessageBox.critical(
                    self, 'something went wrong!',
                    'could not add/remove collection: %s' % e.message)
            finally:
                self.__insideAuthCallback = False
Ejemplo n.º 10
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.proxyModel = QSortFilterProxyModel()
        self.proxyModel.setDynamicSortFilter(True)

        self.sourceGroupBox = QGroupBox("Original Model")
        self.proxyGroupBox = QGroupBox("Sorted/Filtered Model")

        self.sourceView = QTreeView()
        self.sourceView.setRootIsDecorated(False)
        self.sourceView.setAlternatingRowColors(True)

        self.proxyView = QTreeView()
        self.proxyView.setRootIsDecorated(False)
        self.proxyView.setAlternatingRowColors(True)
        self.proxyView.setModel(self.proxyModel)
        self.proxyView.setSortingEnabled(True)

        self.sortCaseSensitivityCheckBox = QCheckBox("Case sensitive sorting")
        self.filterCaseSensitivityCheckBox = QCheckBox("Case sensitive filter")

        self.filterPatternLineEdit = QLineEdit()
        self.filterPatternLineEdit.setClearButtonEnabled(True)
        self.filterPatternLabel = QLabel("&Filter pattern:")
        self.filterPatternLabel.setBuddy(self.filterPatternLineEdit)

        self.filterSyntaxComboBox = QComboBox()
        self.filterSyntaxComboBox.addItem("Regular expression",
                                          REGULAR_EXPRESSION)
        self.filterSyntaxComboBox.addItem("Wildcard",
                                          WILDCARD)
        self.filterSyntaxComboBox.addItem("Fixed string",
                                          FIXED_STRING)
        self.filterSyntaxLabel = QLabel("Filter &syntax:")
        self.filterSyntaxLabel.setBuddy(self.filterSyntaxComboBox)

        self.filterColumnComboBox = QComboBox()
        self.filterColumnComboBox.addItem("Subject")
        self.filterColumnComboBox.addItem("Sender")
        self.filterColumnComboBox.addItem("Date")
        self.filterColumnLabel = QLabel("Filter &column:")
        self.filterColumnLabel.setBuddy(self.filterColumnComboBox)

        self.filterPatternLineEdit.textChanged.connect(self.filterRegExpChanged)
        self.filterSyntaxComboBox.currentIndexChanged.connect(self.filterRegExpChanged)
        self.filterColumnComboBox.currentIndexChanged.connect(self.filterColumnChanged)
        self.filterCaseSensitivityCheckBox.toggled.connect(self.filterRegExpChanged)
        self.sortCaseSensitivityCheckBox.toggled.connect(self.sortChanged)

        sourceLayout = QHBoxLayout()
        sourceLayout.addWidget(self.sourceView)
        self.sourceGroupBox.setLayout(sourceLayout)

        proxyLayout = QGridLayout()
        proxyLayout.addWidget(self.proxyView, 0, 0, 1, 3)
        proxyLayout.addWidget(self.filterPatternLabel, 1, 0)
        proxyLayout.addWidget(self.filterPatternLineEdit, 1, 1, 1, 2)
        proxyLayout.addWidget(self.filterSyntaxLabel, 2, 0)
        proxyLayout.addWidget(self.filterSyntaxComboBox, 2, 1, 1, 2)
        proxyLayout.addWidget(self.filterColumnLabel, 3, 0)
        proxyLayout.addWidget(self.filterColumnComboBox, 3, 1, 1, 2)
        proxyLayout.addWidget(self.filterCaseSensitivityCheckBox, 4, 0, 1, 2)
        proxyLayout.addWidget(self.sortCaseSensitivityCheckBox, 4, 2)
        self.proxyGroupBox.setLayout(proxyLayout)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.sourceGroupBox)
        mainLayout.addWidget(self.proxyGroupBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Basic Sort/Filter Model")
        self.resize(500, 450)

        self.proxyView.sortByColumn(1, Qt.AscendingOrder)
        self.filterColumnComboBox.setCurrentIndex(1)

        self.filterPatternLineEdit.setText("Andy|Grace")
        self.filterCaseSensitivityCheckBox.setChecked(True)
        self.sortCaseSensitivityCheckBox.setChecked(True)

    def setSourceModel(self, model):
        self.proxyModel.setSourceModel(model)
        self.sourceView.setModel(model)

    def filterRegExpChanged(self):
        syntax_nr = self.filterSyntaxComboBox.currentData()
        pattern = self.filterPatternLineEdit.text()
        if syntax_nr == WILDCARD:
            pattern = QRegularExpression.wildcardToRegularExpression(pattern)
        elif syntax_nr == FIXED_STRING:
            pattern = QRegularExpression.escape(pattern)

        regExp = QRegularExpression(pattern)
        if not self.filterCaseSensitivityCheckBox.isChecked():
            options = regExp.patternOptions()
            options |= QRegularExpression.CaseInsensitiveOption
            regExp.setPatternOptions(options)
        self.proxyModel.setFilterRegularExpression(regExp)

    def filterColumnChanged(self):
        self.proxyModel.setFilterKeyColumn(self.filterColumnComboBox.currentIndex())

    def sortChanged(self):
        if self.sortCaseSensitivityCheckBox.isChecked():
            caseSensitivity = Qt.CaseSensitive
        else:
            caseSensitivity = Qt.CaseInsensitive

        self.proxyModel.setSortCaseSensitivity(caseSensitivity)
Ejemplo n.º 11
0
class ExtendedComboBox(QComboBox):
    def __init__(self, parent=None):
        super(ExtendedComboBox, self).__init__(parent)

        #self.setFocusPolicy(Qt.StrongFocus)
        #self.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        #        self.setStyleSheet('''
        #QComboBox { min-width: 1px}
        #QComboBox QAbstractItemView::item { min-width: 200px;}"
        #''')
        self.setEditable(True)
        self.setVisible(True)

        # add a filter model to filter matching items
        self.pFilterModel = QSortFilterProxyModel(self)
        self.pFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.pFilterModel.setSourceModel(self.model())

        # add a completer, which uses the filter model
        self.completer = QCompleter(self.pFilterModel, self)
        # always show all (filtered) completions
        self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.setCompleter(self.completer)

        # connect signals
        self.lineEdit().textEdited.connect(
            self.pFilterModel.setFilterFixedString)
        self.completer.activated.connect(self.on_completer_activated)

    # on selection of an item from the completer, select the corresponding item from combobox
    def on_completer_activated(self, text):
        if text:
            index = self.findText(text)
            self.setCurrentIndex(index)
            self.activated[str].emit(self.itemText(index))

    # on model change, update the models of the filter and completer as well
    def setModel(self, model):
        super(ExtendedComboBox, self).setModel(model)
        self.pFilterModel.setSourceModel(model)
        self.completer.setModel(self.pFilterModel)

    # on model column change, update the model column of the filter and completer as well
    def setModelColumn(self, column):
        self.completer.setCompletionColumn(column)
        self.pFilterModel.setFilterKeyColumn(column)
        super(ExtendedComboBox, self).setModelColumn(column)


#if __name__ == "__main__":

#    app = QApplication(sys.argv)
#    string_list = ['hola muchachos', 'adios amigos', 'hello world', 'good bye']
#    combo = ExtendedComboBox()
#    # either fill the standard model of the combobox
#    combo.addItems(string_list)

#    # or use another model
#    #combo.setModel(QStringListModel(string_list))

#    combo.resize(300, 40)
#    combo.show()

#    sys.exit(app.exec_())
Ejemplo n.º 12
0
    class __HPasteCollectionWidget(CollectionWidget):
        def __init__(self, parent=None):
            super(HPasteCollectionWidget.__HPasteCollectionWidget,
                  self).__init__(parent,
                                 metadataExposedKeys=('raw_url', 'nettype'))
            for x in xrange(1, 5):
                self.ui.mainView.horizontalHeader().hideSection(x)

            self.__nepane = None
            self.__netType = ''

            self.__nettypeFilter = QSortFilterProxyModel(self)
            self.__nettypeFilter.setFilterKeyColumn(4)
            self.__nettypeFilter.setFilterRegExp(
                QRegExp("*", Qt.CaseInsensitive, QRegExp.Wildcard))
            self.appendFilter(self.__nettypeFilter)

            self.accepted.connect(self.doOnAccept)

        def setNetworkEditor(self, pane):
            if (not isinstance(pane, hou.NetworkEditor)):
                pane = None

            self.__nepane = pane  #save to position pasted nodes in it

            if (pane is None):
                nettype = '*'
                self.__netType = ''  #Used to create new snippet types
            else:
                nettype = hpaste.getChildContext(pane.pwd(),
                                                 hou.applicationVersion())
                self.__netType = nettype
            self.__nettypeFilter.setFilterRegExp(
                QRegExp(nettype, Qt.CaseInsensitive, QRegExp.Wildcard))

        @Slot(object)
        def doOnAccept(self, item):
            if (item is None): return
            try:
                hou.clearAllSelected()
                hpaste.stringToNodes(item.content(), ne=self.__nepane)
            except Exception as e:
                hou.ui.displayMessage("could not paste: %s" % e.message,
                                      severity=hou.severityType.Warning)

        def _addItem(self, collection):
            #Please, dont throw from here!
            try:
                nodes = hou.selectedItems()
            except:
                nodes = hou.selectedNodes()
            if (len(nodes) == 0):
                QMessageBox.warning(self, 'not created',
                                    'selection is empty, nothing to add')
                return

            while True:
                #btn,(name,desc) = (0,('1','2'))#hou.ui.readMultiInput('enter some information about new item',('name','description'),buttons=('Ok','Cancel'))
                name, desc, public, good = QDoubleInputDialog.getDoubleTextCheckbox(
                    self, 'adding a new item to %s' % collection.name(),
                    'enter new item details', 'name', 'description', 'public',
                    '', 'a snippet', False)
                if (not good): return

                if (len(name) > 0):
                    break
                    #validity check

            try:
                #print(name)
                #print(desc)
                #print(hpaste.nodesToString(nodes))
                self.model().addItemToCollection(
                    collection,
                    name,
                    desc,
                    hpaste.nodesToString(nodes),
                    public,
                    metadata={'nettype': self.__netType})
            except CollectionSyncError as e:
                QMessageBox.critical(self, 'something went wrong!',
                                     'Server error occured: %s' % e.message)

        def _changeAccess(self, index):
            item = index.internalPointer()
            text, good = QInputDialog.getItem(
                None,
                'modify item access',
                'choose new access type:', ['private', 'public'],
                current=item.access() == CollectionItem.AccessType.public,
                editable=False)
            if (not good): return
            newaccess = CollectionItem.AccessType.public if text == 'public' else CollectionItem.AccessType.private
            if (newaccess == item.access()): return
            item.setAccess(newaccess)

        def _replaceContent(self, index):
            try:
                nodes = hou.selectedItems()
            except:
                nodes = hou.selectedNodes()
            if (len(nodes) == 0):
                QMessageBox.warning(self, 'cannot replace',
                                    'selection is empty')
                return
            item = index.internalPointer()
            good = QMessageBox.warning(
                self, 'sure?',
                'confirm that you want to replace the content of selected item "%s". This operation can not be undone.'
                % item.name(),
                QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok
            if (not good): return
            try:
                item.setContent(hpaste.nodesToString(nodes))
            except CollectionSyncError as e:
                QMessageBox.critical(self, 'something went wrong!',
                                     'Server error occured: %s' % e.message)

        def _itemInfo(self, index):
            item = index.internalPointer()
            accesstext = 'public' if item.access(
            ) == CollectionItem.AccessType.public else 'private'
            readonlytext = 'readonly' if item.readonly() else 'editable'
            info = 'name: %s\n%s\naccess: %s\n%s\n\ncollection id: %s\n\nmetadata:\n' % (
                item.name(), item.description(), accesstext, readonlytext,
                item.id())
            info += '\n'.join(('%s : %s' % (key, item.metadata()[key])
                               for key in item.metadata()))

            QMessageBox.information(self, 'item information', info)

        def _renameItem(self, index):
            item = index.internalPointer()
            oldname = item.name()
            olddesc = item.description()
            newname, newdesc, good = QDoubleInputDialog.getDoubleText(
                self, 'modify item info',
                'Enter new item name and description', 'name', 'description',
                oldname, olddesc)
            if (not good): return
            if (newname != oldname): item.setName(newname)
            if (newdesc != olddesc): item.setDescription(newdesc)

        #def _replaceContent(self, index):
        #pass

        def _confirmRemove(self, index):
            return QMessageBox.warning(
                self, 'sure?',
                'confirm removing the item from collection. This operation can not be undone.',
                QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok
Ejemplo n.º 13
0
class TdisMainForm(QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.setWindowTitle("Родословная")
        self.resize(800, self.height())
        self.distance = 1000

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        layout = QGridLayout()
        self.central_widget.setLayout(layout)

        self.lb_find = QInvisibleButton('Поиск')
        self.lb_find.setFont(mainfont)
        self.te_find = QLineEdit()
        self.te_find.setFont(mainfont)

        layout.addWidget(self.te_find, 0, 0, 1, 1)
        layout.addWidget(self.lb_find, 0, 0, 1, 1)
        #if mode:
        #   te.setReadOnly(False)
        self.lb_find.clicked.connect(self.button_pressed)
        self.te_find.returnPressed.connect(self.line_edit_return_pressed)

        self.table = QTableView()  # Создаём таблицу
        self.table.doubleClicked.connect(self.viewPerson)
        layout.addWidget(self.table)
        self.table.setFocus()
        timer = QTimer(self)
        timer.singleShot(0, self.async_init)

    def async_init(self):
        self.database = AllTables('database/objects')

        self.model = TableModel(self.database.get_peoples())
        self.table.setModel(self.model)
        self.table.resizeRowsToContents()
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.model.dataChanged.connect(self.table.update)

        # Работаем с выпадающим меню
        def openMenu(position):
            menu = QMenu()
            relAction = menu.addAction('Связи')
            menu.addSeparator()
            albAction = menu.addAction('Альбомы')
            menu.addSeparator()
            miniatureAction = menu.addAction('Миниатюра')
            menu.addSeparator()
            viewAction = menu.addAction('Просмотреть')
            addAction = menu.addAction('Добавить')
            editAction = menu.addAction('Редактировать')
            delAction = menu.addAction('Удалить')
            menu.addSeparator()
            drawGraphAction = menu.addAction('Построить дерево')
            menu.addSeparator()
            quitAction = menu.addAction('Выход')
            action = menu.exec_(self.table.mapToGlobal(position))

            if action == viewAction:
                self.viewPerson()

            if action == miniatureAction:
                p = self.get_selected_people()
                print('p = ' + str(p))
                if p is not None:
                    photo_ids = self.database.get_all_photo_ids(p['pid'])
                    path = 0
                    if photo_ids and type(photo_ids) == type(
                        []) and len(photo_ids) > 0:
                        path = self.database.get_photo_path(
                            p['pid'], photo_ids[0])
                    gm = GalleryMiniature(p['pid'], path)
                    gm.exec()

            if action == albAction:
                p = self.get_selected_people()
                if p is not None:
                    self.albuns = AlbumViewer(p['pid'], self.database, 1)
                    self.albuns.show()

            if action == addAction:
                self.personal_card = PersonalCard(
                    self.database.get_people(self.database.add_people({})),
                    self.database, 1)
                self.personal_card.exec_()

                self.line_edit_return_pressed()

            if action == editAction:
                p = self.get_selected_people()
                if p is not None:
                    self.personal_card = PersonalCard(p, self.database, 1)
                    self.personal_card.exec_()

                    self.line_edit_return_pressed()

            if action == delAction:
                res = QMessageBox.question(
                    self, 'ВНИМАНИЕ!!!',
                    "Вы действительно хотите выполнить удаление?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if res == QMessageBox.Yes:
                    select = self.table.selectionModel()
                    if select.hasSelection():
                        id_list = [
                            index.data() for index in
                            self.table.selectionModel().selection().indexes()
                            if index.column() == 0
                        ]
                        print(id_list)
                        self.database.del_people(id_list)
                        self.database.peoples.save()
                        for pid in id_list:
                            print('remove = ' + str(self.model.removeRow(pid)))

                    self.line_edit_return_pressed()

            if action == relAction:
                pid = self.get_selected_pid()
                backup_relations = copy.deepcopy(self.database.relations)
                self.relation_card = RelationCard(pid, self.database, 2)
                if not self.relation_card.exec_():
                    self.database.relations = backup_relations

            if action == drawGraphAction:
                print('draw graph')
                #dialog = MyDialog()
                #dialog.exec_()
                #engine = dialog.engine
                engine = 'dot'
                self.gd = GraphDrawer(self.database, engine)

            if action == quitAction:
                qApp.quit()

        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(openMenu)

    def get_selected_pid(self):
        pid_list = [
            index.data()
            for index in self.table.selectionModel().selection().indexes()
            if index.column() == 0
        ]
        if len(pid_list) == 1:
            return int(pid_list[0])
        return None

    def get_selected_people(self):
        pid_list = [
            index.data()
            for index in self.table.selectionModel().selection().indexes()
            if index.column() == 0
        ]
        if len(pid_list) == 1:
            return self.database.get_people(int(pid_list[0]))
        return None

    def viewPerson(self):
        p = self.get_selected_people()
        if p is not None:
            self.personal_card = PersonalCard(p, self.database, 0)
            self.personal_card.show()

    def button_pressed(self):
        self.lb_find.stackUnder(self.te_find)
        self.te_find.setFocus()

    def line_edit_return_pressed(self):
        print(self.te_find.text())

        self.model = TableModel(self.database.get_peoples())

        self.proxy_model = QSortFilterProxyModel(self.model)
        self.proxy_model.setSourceModel(self.model)
        self.proxy_model.setFilterFixedString(self.te_find.text())
        self.proxy_model.setFilterKeyColumn(-1)

        self.table.setModel(self.proxy_model)
        self.table.update()
        self.table.resizeRowsToContents()

        #sender = self.sender()
        self.te_find.stackUnder(self.lb_find)
        self.lb_find.setFocus()
Ejemplo n.º 14
0
class QStringTable(QTableView):
    def __init__(self, parent, selection_callback=None):
        super(QStringTable, self).__init__(parent)

        self._selected = selection_callback
        self._filter = None

        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setShowGrid(False)
        self.verticalHeader().setVisible(False)
        self.verticalHeader().setDefaultSectionSize(24)
        self.setHorizontalScrollMode(self.ScrollPerPixel)

        self._model = QStringModel(None)
        self._proxy = QSortFilterProxyModel(self)
        self._proxy.setSourceModel(self._model)
        self._proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.setModel(self._proxy)

        self.setSortingEnabled(True)
        self.setSelectionMode(QAbstractItemView.SingleSelection)

        # let the last column (string) fill table width
        self.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)

        self.doubleClicked.connect(self._on_string_selected)

    #
    # Properties
    #

    @property
    def cfg(self):
        return self._model.cfg

    @cfg.setter
    def cfg(self, v):
        self._model.cfg = v
        self.fast_resize()

    @property
    def xrefs(self):
        return self._model.xrefs

    @xrefs.setter
    def xrefs(self, v):
        self._model.xrefs = v

    @property
    def function(self):
        return self._model.function

    @function.setter
    def function(self, v):
        self._model.function = v
        self.fast_resize()

    @property
    def filter_string(self):
        return self._filter

    @filter_string.setter
    def filter_string(self, v):
        self._filter = v
        if isinstance(v, re.Pattern):
            self._proxy.setFilterRegExp(self._filter.pattern)
        else:
            self._proxy.setFilterWildcard(self._filter)
        self._proxy.setFilterKeyColumn(2)

    #
    # Public methods
    #

    def fast_resize(self):
        self.setVisible(False)
        self.resizeColumnsToContents()
        self.setVisible(True)

    #
    # Event handlers
    #

    def _on_string_selected(self, model_index):
        model_index = self._proxy.mapToSource(model_index)
        selected_index = model_index.row()
        if self._model is None:
            return
        if 0 <= selected_index < len(self._model.values):
            selected_item = self._model.values[selected_index]
        else:
            selected_item = None

        if self._selected is not None:
            self._selected(selected_item)
Ejemplo n.º 15
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        hlayout = QHBoxLayout()

        layout = QVBoxLayout()

        self.filtert = QLineEdit()
        self.filtert.setPlaceholderText("Search...")
        self.table = QTableView()

        vlayout = QVBoxLayout()
        vlayout.addWidget(self.filtert)
        vlayout.addWidget(self.table)

        # Left/right pane.
        hlayout.addLayout(vlayout)
        hlayout.addLayout(layout)

        form = QFormLayout()

        self.track_id = QSpinBox()
        self.track_id.setDisabled(True)
        self.track_id.setRange(0, 2147483647)
        self.name = QLineEdit()
        self.album = QComboBox()
        self.media_type = QComboBox()
        self.genre = QComboBox()
        self.composer = QLineEdit()

        self.milliseconds = QSpinBox()
        self.milliseconds.setRange(0, 2147483647)
        self.milliseconds.setSingleStep(1)

        self.bytes = QSpinBox()
        self.bytes.setRange(0, 2147483647)
        self.bytes.setSingleStep(1)

        self.unit_price = QDoubleSpinBox()
        self.unit_price.setRange(0, 999)
        self.unit_price.setSingleStep(0.01)
        self.unit_price.setPrefix("$")

        form.addRow(QLabel("Track ID"), self.track_id)
        form.addRow(QLabel("Track name"), self.name)
        form.addRow(QLabel("Composer"), self.composer)
        form.addRow(QLabel("Milliseconds"), self.milliseconds)
        form.addRow(QLabel("Bytes"), self.bytes)
        form.addRow(QLabel("Unit Price"), self.unit_price)

        self.model = QSqlTableModel(db=db)

        self.proxy_model = QSortFilterProxyModel()
        self.proxy_model.setSourceModel(self.model)
        self.proxy_model.sort(1, Qt.AscendingOrder)
        self.proxy_model.setFilterKeyColumn(-1)  # all columns
        self.table.setModel(self.proxy_model)

        # Update search when filter changes.
        self.filtert.textChanged.connect(self.proxy_model.setFilterFixedString)

        self.mapper = QDataWidgetMapper()
        self.mapper.setModel(self.proxy_model)

        self.mapper.addMapping(self.track_id, 0)
        self.mapper.addMapping(self.name, 1)
        self.mapper.addMapping(self.composer, 5)
        self.mapper.addMapping(self.milliseconds, 6)
        self.mapper.addMapping(self.bytes, 7)
        self.mapper.addMapping(self.unit_price, 8)

        self.model.setTable("Track")
        self.model.select()

        # Change the mapper selection using the table.
        self.table.selectionModel().currentRowChanged.connect(
            self.mapper.setCurrentModelIndex)

        self.mapper.toFirst()

        # tag::controls[]
        self.setMinimumSize(QSize(800, 400))

        controls = QHBoxLayout()

        prev_rec = QPushButton("Previous")
        prev_rec.clicked.connect(self.mapper.toPrevious)

        next_rec = QPushButton("Next")
        next_rec.clicked.connect(self.mapper.toNext)

        save_rec = QPushButton("Save Changes")
        save_rec.clicked.connect(self.mapper.submit)

        controls.addWidget(prev_rec)
        controls.addWidget(next_rec)
        controls.addWidget(save_rec)

        layout.addLayout(form)
        layout.addLayout(controls)

        widget = QWidget()
        widget.setLayout(hlayout)
        self.setCentralWidget(widget)
Ejemplo n.º 16
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.blockSignals(True)
        self.person = Person()
        self.blockSignals(False)
        self.type_res = Restriction(RESTRICT_TYPES_FILE)
        self.fd_res = Restriction(RESTRICT_FDS_FILE)

        self.setup_fridge_views()
        self.setup_connections()
        self.update_fridge_line_edit_placeholder()

        self.add_foods_btn.setFocus()
        self.display_empty_nutrition()
        self.showMaximized()
        self.read_settings()
        self.show()

    def update_fridge_line_edit_placeholder(self):
        number = len(self.person.foods)
        plural = '' if number == 1 else 's'
        text = '🔍 Search fridge ({number} item{plural})'.format(
            number=number, plural=plural)
        self.fridge_line_edit.setPlaceholderText(text)

    def fridge_line_edit_changed(self):
        reg_exp = QRegExp(self.fridge_line_edit.text(), Qt.CaseInsensitive)
        self.fridge_filter_model.setFilterRegExp(reg_exp)

    def setup_fridge_views(self):
        self.fridge_model = FridgeModel(foods=self.person.foods)
        self.fridge_filter_model = QSortFilterProxyModel(self)
        self.fridge_filter_model.setSourceModel(self.fridge_model)

        self.fridge_view.setModel(self.fridge_filter_model)
        self.prices_view.setModel(self.fridge_filter_model)
        self.constraints_view.setModel(self.fridge_filter_model)
        self.nut_quant_view.setModel(self.fridge_filter_model)

        self.fridge_filter_model.setFilterKeyColumn(NAME_COL)

        # Hide col
        hide_view_cols(self.fridge_view, F_COLS_TO_HIDE)
        hide_view_cols(self.prices_view, P_COLS_TO_HIDE)
        hide_view_cols(self.constraints_view, C_COLS_TO_HIDE)
        hide_view_cols(self.nut_quant_view, N_COLS_TO_HIDE)

        # Header must be explicitly set to visible even if set in Designer
        self.fridge_view.horizontalHeader().setVisible(True)
        self.prices_view.horizontalHeader().setVisible(True)
        self.constraints_view.horizontalHeader().setVisible(True)
        self.nut_quant_view.horizontalHeader().setVisible(True)

        # Set column width
        self.prices_view.setColumnWidth(PRICE_COL, VALUE_COL_WIDTH)
        self.prices_view.setColumnWidth(PER_COL, PER_COL_WIDTH)
        self.prices_view.setColumnWidth(PRICE_QUANTITY_COL, VALUE_COL_WIDTH)

        self.constraints_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.nut_quant_view.setColumnWidth(NUT_QUANT_COL, VALUE_COL_WIDTH)

        # Set row height
        set_v_header_height(self.fridge_view, FRIDGE_V_HEADER_SIZE)
        set_v_header_height(self.prices_view, FRIDGE_V_HEADER_SIZE)
        set_v_header_height(self.constraints_view, FRIDGE_V_HEADER_SIZE)
        set_v_header_height(self.nut_quant_view, FRIDGE_V_HEADER_SIZE)

        set_header_font(self.fridge_view, FONT_MAIN_SIZE, QFont.DemiBold)
        set_header_font(self.prices_view, FONT_MAIN_SIZE, QFont.DemiBold)
        set_header_font(self.constraints_view, FONT_MAIN_SIZE, QFont.DemiBold)
        set_header_font(self.nut_quant_view, FONT_MAIN_SIZE, QFont.DemiBold)

        # Set header fixed
        self.fridge_view.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.prices_view.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        #self.constraints_view.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.nut_quant_view.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)

        # Hide fridge scrollbar
        self.fridge_view.verticalScrollBar().setStyleSheet(
            "QScrollBar {width:0px;}")

    def display_empty_nutrition(self):
        macros, vits, minerals = get_empty_nutrition(self.person)

        macros_model = NutritionTableModel(nutrients=macros, nutrient_group='General')
        vits_model = NutritionTableModel(nutrients=vits, nutrient_group='Vitamins')
        minerals_model = NutritionTableModel(
            nutrients=minerals, nutrient_group='Minerals')

        self.setup_nutrition_view(self.macros_view, macros_model)
        self.setup_nutrition_view(self.vits_view, vits_model)
        self.setup_nutrition_view(self.minerals_view, minerals_model)

    def display_nutrition(self):
        selected_food_id_ixs = self.fridge_view.selectionModel().selectedRows()
        if len(selected_food_id_ixs) == 0:
            self.display_empty_nutrition()
            return

        selected_food_ids = [ix.data() for ix in selected_food_id_ixs]
        selected_food_amounts = [ix.siblingAtColumn(
            NUT_QUANT_COL).data() for ix in selected_food_id_ixs]
        selected_food_units = [ix.siblingAtColumn(
            NUT_QUANT_UNIT_COL).data() for ix in selected_food_id_ixs]

        # Convert non-gram quantities to grams
        for i, (unit, food_id, amount) in enumerate(zip(selected_food_units, selected_food_ids, selected_food_amounts)):
            if unit != 'g':
                converted_amount = convert_quantity(amount, unit)
                selected_food_amounts[i] = converted_amount

        macros, vits, minerals = get_nutrition(
            self.person, selected_food_ids, selected_food_amounts)

        macros_model = NutritionTableModel(nutrients=macros, nutrient_group='General')
        vits_model = NutritionTableModel(nutrients=vits, nutrient_group='Vitamins')
        minerals_model = NutritionTableModel(nutrients=minerals, nutrient_group='Minerals')

        self.setup_nutrition_view(self.macros_view, macros_model)
        self.setup_nutrition_view(self.vits_view, vits_model)
        self.setup_nutrition_view(self.minerals_view, minerals_model)

    def setup_nutrition_view(self, view, model):
        view.setModel(model)

        view.setItemDelegate(ProgressBarDelegate(self))

        set_header_font(view, FONT_MAIN_SIZE, QFont.DemiBold)
        set_column_widths(view, nut_col_to_attr.keys(), nut_col_widths)
        view.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        vertical_resize_table_view_to_contents(view)

    def remove_from_fridge(self):
        selected_food_id_indexes = self.fridge_view.selectionModel().selectedRows()
        food_ids = []
        for index in selected_food_id_indexes:
            food_ids.append(index.data(Qt.DisplayRole))

        row = selected_food_id_indexes[0].row()
        count = selected_food_id_indexes[-1].row() - row + 1

        self.fridge_filter_model.removeRows(row, count)
        self.person.remove_foods_from_db(food_ids=food_ids)

    def update_foods(self, index):
        if index.column() != FOOD_ID_COL:
            food = self.person.foods[index.row()]
            self.person.update_food_in_user_db(food=food)

    def open_search_window(self):
        self.search_window = SearchWindow(self, self.person, self.fridge_model, self.type_res, self.fd_res)
        self.search_window.setAttribute(Qt.WA_DeleteOnClose)

    def open_pref(self):
        self.pref_window = PrefWindow(
            parent=self, person=self.person, type_res=self.type_res, fd_res=self.fd_res)
        self.pref_window.setAttribute(Qt.WA_DeleteOnClose)

    def optimize(self):
        if len(self.person.foods) == 0:
            return

        self.optimum_diet_window = OptimumDietWindow(self.person, self.type_res, self.fd_res, self)
        self.optimum_diet_window.setAttribute(Qt.WA_DeleteOnClose)

    def toggle_remove_btn(self):
        if self.fridge_view.selectionModel() is None:
            self.remove_btn.setEnabled(False)
        elif len(self.fridge_view.selectionModel().selectedRows()) > 0:
            self.remove_btn.setEnabled(True)
        else:
            self.remove_btn.setEnabled(False)

    def setup_connections(self):
        self.fridge_model.dataChanged.connect(self.update_foods)
        self.fridge_model.dataChanged.connect(self.display_nutrition)

        self.fridge_view.selectionModel().selectionChanged.connect(self.display_nutrition)

        # Update filtered view
        self.fridge_line_edit.textChanged.connect(
            self.fridge_line_edit_changed)

        # Update fridge search placeholder
        self.fridge_model.rowsInserted.connect(
            self.update_fridge_line_edit_placeholder)
        self.fridge_model.rowsRemoved.connect(
            self.update_fridge_line_edit_placeholder)

        # Synchronize fridge selection to prices and constraints
        self.prices_view.setSelectionModel(self.fridge_view.selectionModel())
        self.constraints_view.setSelectionModel(
            self.fridge_view.selectionModel())
        self.nut_quant_view.setSelectionModel(
            self.fridge_view.selectionModel())

        # Synchronize scrollbars
        self.fridge_view.verticalScrollBar().valueChanged.connect(
            self.prices_view.verticalScrollBar().setValue)
        self.prices_view.verticalScrollBar().valueChanged.connect(
            self.fridge_view.verticalScrollBar().setValue)

        self.fridge_view.verticalScrollBar().valueChanged.connect(
            self.constraints_view.verticalScrollBar().setValue)
        self.constraints_view.verticalScrollBar().valueChanged.connect(
            self.fridge_view.verticalScrollBar().setValue)

        self.fridge_view.verticalScrollBar().valueChanged.connect(
            self.nut_quant_view.verticalScrollBar().setValue)
        self.nut_quant_view.verticalScrollBar().valueChanged.connect(
            self.fridge_view.verticalScrollBar().setValue)

        # Add to fridge button
        self.add_foods_btn.clicked.connect(self.open_search_window)

        # Remove button
        self.remove_btn.clicked.connect(self.remove_from_fridge)
        self.fridge_view.selectionModel().selectionChanged.connect(self.toggle_remove_btn)

        # Optimize button
        self.optimize_btn.clicked.connect(self.optimize)

        # Settings button
        self.pref_btn.clicked.connect(self.open_pref)

    def closeEvent(self, event):
        settings = QSettings("spartan", "spartan")
        settings.setValue("geometry", self.saveGeometry())
        settings.setValue("windowState", self.saveState())
        super().closeEvent(event)

    def read_settings(self):
        settings = QSettings("spartan", "spartan")
        self.restoreGeometry(settings.value("geometry"))
        self.restoreState(settings.value("windowState"))
Ejemplo n.º 17
0
class MainWindow(QMainWindow):
    createUpload = Signal(list, htauthcontroller.HTAuthorizationController,
                          str, list)

    def __init__(self):
        super(MainWindow, self).__init__()
        self.hyperthoughtui = HyperthoughtDialogImpl()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.TabWidget.setCurrentWidget(self.ui.CreateTemplateTab)
        self.ui.actionHelp.triggered.connect(self.help)
        self.ui.actionOpenPackage.triggered.connect(self.openPackage)
        self.ui.actionSave_Package.triggered.connect(self.savePackageAs)
        self.ui.actionClose.triggered.connect(self.close)
        self.ui.actionSave_Template.triggered.connect(self.saveTemplate)
        self.ui.actionOpen_Template.triggered.connect(self.restoreTemplate)
        self.ui.dataFileSelect.clicked.connect(self.selectFile)
        self.ui.hyperthoughtTemplateSelect.clicked.connect(self.selectTemplate)
        self.ui.saveTemplateButton.clicked.connect(self.saveTemplate)
        self.ui.otherDataFileSelect.clicked.connect(self.extractFile)
        self.ui.hyperthoughtUploadButton.clicked.connect(
            self.uploadToHyperthought)
        self.setAcceptDrops(True)
        self.numCustoms = 0
        self.customInputs = []
        self.templateFilePath = ""

        aTree = {}
        self.createtablemodel = TableModelC(aTree, self)
        self.filterModel = FilterModel(self)
        self.filterModel.setSourceModel(self.createtablemodel)
        self.ui.metadataTableView.setModel(self.filterModel)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_SOURCE_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_HTNAME_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_SOURCEVAL_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_HTVALUE_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.setColumnWidth(
            self.createtablemodel.K_USESOURCE_COL_INDEX,
            self.width() * .1)

        self.checkboxDelegate = CheckBoxDelegate()
        self.createtrashDelegate = TrashDelegate()
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_USESOURCE_COL_INDEX, self.checkboxDelegate)
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_EDITABLE_COL_INDEX, self.checkboxDelegate)
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_REMOVE_COL_INDEX, self.createtrashDelegate)
        self.ui.metadataTableView.setColumnWidth(
            self.createtablemodel.K_REMOVE_COL_INDEX,
            self.width() * .05)

        self.treeModel = TreeModel(["Available File Metadata"], aTree,
                                   self.createtablemodel)
        self.ui.metadataTreeView.setModel(self.treeModel)
        self.treeModel.checkChanged.connect(self.filterModel.checkList)
        self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)
        self.editableKeys = []

        self.usetablemodel = TableModelU(self, [], self.editableKeys)
        self.usefilterModel = FilterModelU(self)
        self.usefilterModel.setSourceModel(self.usetablemodel)
        self.ui.useTemplateTableView.setModel(self.usefilterModel)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTKEY_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTVALUE_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_SOURCE_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_USESOURCE_COL_INDEX,
            self.width() * .1)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTANNOTATION_COL_INDEX,
            self.width() * .1)
        self.usetrashDelegate = TrashDelegate()
        self.ui.useTemplateTableView.setItemDelegateForColumn(
            self.usetablemodel.K_USESOURCE_COL_INDEX, self.checkboxDelegate)
        self.ui.useTemplateTableView.setItemDelegateForColumn(
            self.usetablemodel.K_REMOVE_COL_INDEX, self.usetrashDelegate)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_REMOVE_COL_INDEX,
            self.width() * .075)
        self.usetrashDelegate.pressed.connect(self.handleRemoveUse)

        self.uselistmodel = ListModel(self, self.usetablemodel, [])
        self.ui.useTemplateListView.setModel(self.uselistmodel)
        self.uselistmodel.rowRemoved.connect(self.toggleButtons)
        self.uselistmodel.rowAdded.connect(self.toggleButtons)

        self.useFileDelegate = UseFileDelegate(self)
        self.ui.useTemplateListView.setItemDelegate(self.useFileDelegate)

        self.ui.useTemplateListView.clicked.connect(
            self.removeRowfromUsefileType)

        self.addAppendButton()
        self.ui.TabWidget.currentChanged.connect(self.movethedamnbutton)
        self.appendSourceFilesButton.clicked.connect(self.addFile)
        self.ui.appendCreateTableRowButton.clicked.connect(
            self.addCreateTableRow)
        self.ui.appendUseTableRowButton.clicked.connect(self.addUseTableRow)
        self.ui.hyperthoughtLocationButton.clicked.connect(
            self.hyperthoughtui.exec)
        self.ui.usetableSearchBar.textChanged.connect(self.filterUseTable)
        self.ui.createTemplateListSearchBar.textChanged.connect(
            self.filterCreateTable)
        self.ui.createTemplateTreeSearchBar.textChanged.connect(
            self.filterCreateTree)
        self.ui.addMetadataFileCheckBox.stateChanged.connect(
            self.checkFileList)

        self.fileType = ""
        self.accessKey = ""
        self.folderuuid = ""
        self.mThread = QThread()
        self.uploader = Uploader()
        self.uploader.moveToThread(self.mThread)
        self.mThread.start()

        self.createUpload.connect(self.uploader.performUpload)
        self.hyperthoughtui.apiSubmitted.connect(self.acceptKey)
        self.hyperthoughtui.finished.connect(self.getLocation)
        self.ui.hyperthoughtTemplateLineEdit.installEventFilter(self)
        self.ui.otherDataFileLineEdit.installEventFilter(self)
        self.ui.dataFileLineEdit.installEventFilter(self)

    def acceptKey(self, apikey):
        self.accessKey = apikey

    def addCreateTableRow(self):
        self.createtablemodel.addEmptyRow(self.numCustoms)
        self.numCustoms += 1

    def addFile(self):
        linetexts = QFileDialog.getOpenFileNames(
            self, self.tr("Select File"),
            QStandardPaths.displayName(QStandardPaths.HomeLocation),
            self.tr("Files (*.ctf *.xml *.ang)"))[0]
        for line in linetexts:
            self.uselistmodel.addRow(line)
        self.toggleButtons()

    def addAppendButton(self):
        self.appendSourceFilesButton = QToolButton(self.ui.useTemplateListView)
        icon = QApplication.style().standardIcon(QStyle.SP_FileIcon)

    def addUseTableRow(self):
        self.usetablemodel.addEmptyRow()

    def checkFileList(self, checked):
        if checked == Qt.Checked:
            if self.ui.otherDataFileLineEdit.text() != "":
                self.uselistmodel.addRow(self.ui.otherDataFileLineEdit.text())
        elif checked == Qt.Unchecked:
            if self.ui.otherDataFileLineEdit.text(
            ) in self.uselistmodel.metadataList:
                rowIndex = self.uselistmodel.metadataList.index(
                    self.ui.otherDataFileLineEdit.text())
                self.uselistmodel.removeRow(rowIndex)

    def closeEvent(self, event):
        self.mThread.quit()
        self.mThread.wait(250)

    def extractFile(self, fileLink=False):
        if fileLink == False:
            linetext = QFileDialog.getOpenFileName(
                self, self.tr("Select File"),
                QStandardPaths.displayName(QStandardPaths.HomeLocation),
                self.tr("Files (*" + self.fileType + ")"))[0]
        else:
            linetext = fileLink
        if linetext != "":
            self.setWindowTitle(linetext)
            self.ui.dataTypeText.setText(linetext.split(".")[1].upper())
            self.ui.otherDataFileLineEdit.setText(linetext)
            if self.ui.addMetadataFileCheckBox.checkState() == Qt.Checked:
                self.uselistmodel.removeAllRows()
                self.uselistmodel.addRow(linetext)
                self.toggleButtons()
            if self.ui.fileParserCombo.findText(
                    linetext.split(".")[1].upper() + " Parser") != -1:
                headerDict = {}
                self.ui.fileParserCombo.setCurrentIndex(
                    self.ui.fileParserCombo.findText(
                        linetext.split(".")[1].upper() + " Parser"))
            if linetext.split(".")[1].upper() == "CTF":
                headerDict = ctf.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "ANG":
                headerDict = ang.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "XML":
                print("XML Parser used")

            if self.templatedata:
                self.usetablemodel.metadataList = []
                self.usefilterModel = FilterModelU(self)
                self.usefilterModel.setSourceModel(self.usetablemodel)
                self.unusedTreeModel = TreeModelU(["Available File Metadata"],
                                                  headerDict,
                                                  self.usetablemodel,
                                                  self.editableKeys)
                self.templatelist = []
                self.templatesources = []
                for i in range(len(self.templatedata)):
                    self.templatelist.append(self.templatedata[i])
                    if "Custom Input" not in self.templatedata[i]["Source"]:
                        self.templatesources.append("/".join(
                            self.templatedata[i]['Source'].split("/")[1:]))
                    else:
                        self.usetablemodel.addExistingRow(self.templatedata[i])
                self.usesearchFilterModel = QSortFilterProxyModel(self)
                self.usesearchFilterModel.setSourceModel(self.usefilterModel)
                self.usesearchFilterModel.setFilterKeyColumn(0)
                self.usesearchFilterModel.setDynamicSortFilter(True)
                self.ui.useTemplateTableView.setModel(
                    self.usesearchFilterModel)

        self.toggleButtons()

    def eventFilter(self, object, event):
        if object == self.ui.hyperthoughtTemplateLineEdit:
            if event.type() == QEvent.DragEnter:
                if str(event.mimeData().urls()[0])[-5:-2] == ".ez":
                    event.acceptProposedAction()
            if (event.type() == QEvent.Drop):
                if str(event.mimeData().urls()[0])[-5:-2] == ".ez":
                    event.acceptProposedAction()
                    self.loadTemplateFile(
                        event.mimeData().urls()[0].toLocalFile())
        if object == self.ui.otherDataFileLineEdit:
            if event.type() == QEvent.DragEnter:
                if str(event.mimeData().urls()[0])[-6:-2] == self.fileType:
                    event.acceptProposedAction()
            if (event.type() == QEvent.Drop):
                if str(event.mimeData().urls()[0])[-6:-2] == self.fileType:
                    event.acceptProposedAction()
                    self.extractFile(event.mimeData().urls()[0].toLocalFile())
        if object == self.ui.dataFileLineEdit:
            if event.type() == QEvent.DragEnter:
                if str(event.mimeData().urls()[0])[-6:-2] == ".ctf" or str(
                        event.mimeData().urls()[0])[-6:-2] == ".ang":
                    event.acceptProposedAction()
            if (event.type() == QEvent.Drop):
                if str(event.mimeData().urls()[0])[-6:-2] == ".ctf" or str(
                        event.mimeData().urls()[0])[-6:-2] == ".ang":
                    event.acceptProposedAction()
                    self.selectFile(event.mimeData().urls()[0].toLocalFile())

        return QMainWindow.eventFilter(self, object, event)

    def filterCreateTable(self):
        self.createTableSearchFilterModel.invalidate()
        self.createTableSearchFilterModel.setFilterCaseSensitivity(
            Qt.CaseInsensitive)
        self.createTableSearchFilterModel.setFilterWildcard(
            "*" + self.ui.createTemplateListSearchBar.text() + "*")

    def filterCreateTree(self):
        self.createTreeSearchFilterModel.invalidate()
        self.createTreeSearchFilterModel.setFilterCaseSensitivity(
            Qt.CaseInsensitive)
        self.createTreeSearchFilterModel.setFilterWildcard(
            "*" + self.ui.createTemplateTreeSearchBar.text() + "*")

    def filterUseTable(self):
        self.usesearchFilterModel.invalidate()
        self.usesearchFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.usesearchFilterModel.setFilterWildcard(
            "*" + self.ui.usetableSearchBar.text() + "*")

    def getLocation(self):
        remoteDirPath = self.hyperthoughtui.getUploadDirectory()
        self.folderuuid = ht_requests.get_ht_id_path_from_ht_path(
            self.hyperthoughtui.authcontrol, ht_path=remoteDirPath)
        self.ui.hyperthoughtLocationLineEdit.setText(remoteDirPath)
        self.toggleButtons()

    def handleRemoveCreate(self, source, filterIndex, tableIndex):
        if "Custom Input" in source:
            for i in range(len(self.createtablemodel.metadataList)):
                if self.createtablemodel.metadataList[i]["Source"] == source:
                    self.createtablemodel.beginRemoveRows(QModelIndex(), i, i)
                    del self.createtablemodel.metadataList[i]
                    self.createtablemodel.endRemoveRows()
                    break
        else:
            self.treeModel.changeLeafCheck(source)

    def handleRemoveUse(self, source, listIndex, filterIndex):
        self.usetablemodel.beginRemoveRows(QModelIndex(), listIndex.row(),
                                           listIndex.row())
        del self.usetablemodel.metadataList[listIndex.row()]
        self.usetablemodel.endRemoveRows()

    def help(self):
        QDesktopServices.openUrl("http://www.bluequartz.net/")

    def movethedamnbutton(self):
        self.appendSourceFilesButton.move(
            self.ui.useTemplateListView.width() -
            self.appendSourceFilesButton.width() - 15,
            self.ui.useTemplateListView.height() -
            self.appendSourceFilesButton.height())

    def openPackage(self):
        linetext = QFileDialog.getOpenFileName(
            self, self.tr("Select File"),
            QStandardPaths.displayName(QStandardPaths.HomeLocation),
            self.tr("Files (*.ezpak)"))[0]
        if linetext != "":

            infile = open(linetext, "r")
            self.loadTemplateFile(infile.readline()[1:-2])
            extractedFile = infile.readline()[1:-2]
            fileList = infile.readline()
            fileList = json.loads(fileList)
            self.fileList = fileList[:]
            self.uselistmodel = ListModel(self, self.usetablemodel,
                                          self.fileList)
            self.ui.useTemplateListView.setModel(self.uselistmodel)
            self.extractFile(extractedFile)
            self.uselistmodel.removeAllRows()
            for i in range(len(fileList)):
                self.uselistmodel.addRow(fileList[i])
            self.toggleButtons()
            infile.close()
            self.ui.TabWidget.setCurrentIndex(1)

    def restoreTemplate(self):
        #Clear data on create side
        self.createtablemodel.metadataList = []
        self.createtablemodel.hiddenList = []
        self.filterModel.displayed = []
        #open template
        linetext = QFileDialog.getOpenFileName(
            self, self.tr("Select File"),
            QStandardPaths.displayName(QStandardPaths.HomeLocation),
            self.tr("Files (*.ez)"))[0]
        if linetext != "":
            infile = open(linetext, "r")
            infile.readline()
            fileType = infile.readline()
            self.fileType = json.loads(fileType)
            infile.readline()
            newList = infile.readline()
            newList = json.loads(newList)
            newDict = infile.readline()
            newDict = json.loads(newDict)
            self.ui.dataTypeText.setText(self.fileType[0][-3:].upper())
            self.ui.fileParserCombo.setCurrentIndex(
                self.ui.fileParserCombo.findText(
                    self.fileType[0][-3:].upper() + " Parser"))
            self.ui.dataFileLineEdit.setText(self.fileType[0])
            self.createtablemodel = TableModelC(newDict, self)
            self.filterModel.displayed = []
            self.filterModel.setSourceModel(self.createtablemodel)
            self.filterModel.fileType = self.fileType
            self.createTableSearchFilterModel = QSortFilterProxyModel(self)
            self.createTableSearchFilterModel.setSourceModel(self.filterModel)
            self.createTableSearchFilterModel.setFilterKeyColumn(1)
            self.createTableSearchFilterModel.setDynamicSortFilter(True)
            self.ui.metadataTableView.setModel(
                self.createTableSearchFilterModel)
            self.treeModel = TreeModelR(["Available File Metadata"], newDict,
                                        self.createtablemodel, newList,
                                        self.filterModel)

            for i in range(len(newList)):
                if "Custom Input" in newList[i]["Source"]:
                    self.numCustoms += 1
                    self.customInputs.append(newList[i])
                    self.createtablemodel.beginInsertRows(
                        self.createtablemodel.index(
                            len(self.createtablemodel.metadataList), 0), i, i)
                    self.createtablemodel.metadataList.append(newList[i])
                    self.createtablemodel.endInsertRows()

            self.createTreeSearchFilterModel = QSortFilterProxyModel(self)
            self.createTreeSearchFilterModel.setSourceModel(self.treeModel)
            self.createTreeSearchFilterModel.setFilterKeyColumn(0)
            self.createTreeSearchFilterModel.setDynamicSortFilter(True)
            self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True)
            self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel)
            self.treeModel.checkChanged.connect(self.filterModel.checkList)
            self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)
            self.ui.TabWidget.setCurrentIndex(0)

    def removeRowfromUsefileType(self, index):
        if self.ui.useTemplateListView.width(
        ) - 64 < self.ui.useTemplateListView.mapFromGlobal(QCursor.pos()).x():
            #this is where to remove the row
            self.uselistmodel.removeRow(index.row())

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.movethedamnbutton()

    def savePackageAs(self):
        fileName = QFileDialog.getSaveFileName(self, "Save File", "/Packages/",
                                               "Packages (*.ezpak)")[0]
        if fileName != "":
            myDir = QDir()
            myDir.mkpath(fileName)
            for file in self.uselistmodel.metadataList:
                QFile.copy(file, fileName + "/" + file.split("/")[-1])

            oldtemplate = open(self.templateFilePath, 'r')
            oldtemplatelist = oldtemplate.readline()
            filetype = oldtemplate.readline()
            oldtemplate.readline()
            oldlist = oldtemplate.readline()
            oldtree = oldtemplate.readline()
            oldtemplate.close()
            with open(fileName + "/" + self.currentTemplate, 'w') as outfile:
                outfile.write(oldtemplatelist)
                outfile.write(filetype)
                json.dump(self.editableKeys, outfile)
                outfile.write("\n")
                outfile.write(oldlist)
                outfile.write(oldtree)

            with open(fileName + "/" + self.currentTemplate + "pak",
                      'w') as outfile:
                json.dump(fileName + "/" + self.currentTemplate, outfile)
                outfile.write("\n")
                json.dump(self.ui.otherDataFileLineEdit.text(), outfile)
                outfile.write("\n")
                json.dump(self.uselistmodel.metadataList, outfile)

    def saveTemplate(self):
        dialog = QFileDialog(self, "Save File", "", "Templates (*.ez)")
        dialog.setDefaultSuffix(".ez")
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        fileName = ""
        if dialog.exec():
            fileName = dialog.selectedFiles()[0]
        if fileName != "":
            with open(fileName, 'w') as outfile:
                json.dump(self.filterModel.displayed, outfile)
                outfile.write("\n")
                json.dump(self.filterModel.fileType, outfile)
                outfile.write("\n")
                self.createtablemodel.editableList = []
                for i in range(len(self.createtablemodel.metadataList)):
                    if self.createtablemodel.metadataList[i][
                            "Editable"] == 2 and (
                                self.createtablemodel.metadataList[i]
                                ["Checked"] == 2 or self.createtablemodel.
                                metadataList[i]["Checked"] == 1):
                        self.createtablemodel.editableList.append(
                            self.createtablemodel.metadataList[i]["Key"])
                json.dump(self.createtablemodel.editableList, outfile)
                outfile.write("\n")
                json.dump(self.createtablemodel.metadataList, outfile)
                outfile.write("\n")
                json.dump(self.treeModel.treeDict, outfile)

    def selectFile(self, fileLink=None):
        if fileLink == False:
            linetext = QFileDialog.getOpenFileName(
                self, self.tr("Select File"),
                QStandardPaths.displayName(QStandardPaths.HomeLocation),
                self.tr("Files (*.*)"))[0]
        else:
            linetext = fileLink
        if linetext != "":
            self.setWindowTitle(linetext)
            self.ui.dataFileLineEdit.setText(linetext)
            self.ui.dataTypeText.setText(linetext.split(".")[1].upper())
            if self.ui.fileParserCombo.findText(
                    linetext.split(".")[1].upper() + " Parser") != -1:
                headerDict = {}
                self.ui.fileParserCombo.setCurrentIndex(
                    self.ui.fileParserCombo.findText(
                        linetext.split(".")[1].upper() + " Parser"))
            if linetext.split(".")[1].upper() == "CTF":
                headerDict = ctf.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "ANG":
                headerDict = ang.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "XML":
                print("XML Parser used")

            self.createtablemodel = TableModelC(headerDict, self)
            self.filterModel.displayed = []
            self.filterModel.setSourceModel(self.createtablemodel)
            self.filterModel.fileType.append(linetext)
            self.createTableSearchFilterModel = QSortFilterProxyModel(self)
            self.createTableSearchFilterModel.setSourceModel(self.filterModel)
            self.createTableSearchFilterModel.setFilterKeyColumn(1)
            self.createTableSearchFilterModel.setDynamicSortFilter(True)
            self.ui.metadataTableView.setModel(
                self.createTableSearchFilterModel)
            self.treeModel = TreeModel(["Available File Metadata"], headerDict,
                                       self.createtablemodel)

            if len(self.customInputs) != 0:
                for i in range(len(self.customInputs)):
                    self.createtablemodel.beginInsertRows(
                        self.createtablemodel.index(
                            len(self.createtablemodel.metadataList), 0), i, i)
                    self.createtablemodel.metadataList.append(
                        self.customInputs[i])
                    self.createtablemodel.endInsertRows()

            self.createTreeSearchFilterModel = QSortFilterProxyModel(self)
            self.createTreeSearchFilterModel.setSourceModel(self.treeModel)
            self.createTreeSearchFilterModel.setFilterKeyColumn(0)
            self.createTreeSearchFilterModel.setDynamicSortFilter(True)
            self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True)
            self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel)
            self.treeModel.checkChanged.connect(self.filterModel.checkList)
            self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)

        self.toggleButtons()
        return True

    def selectTemplate(self):
        startLocation = self.ui.hyperthoughtTemplateLineEdit.text()
        if startLocation == "":
            startLocation = QStandardPaths.writableLocation(
                QStandardPaths.HomeLocation)

        templateFilePath = QFileDialog.getOpenFileName(
            self, self.tr("Select File"), startLocation,
            self.tr("Files (*.ez)"))[0]
        self.loadTemplateFile(templateFilePath)

    def loadTemplateFile(self, templateFilePath=None):
        if templateFilePath == "":
            return False
        self.templateFilePath = templateFilePath
        self.usetablemodel.metadataList = []
        self.usefilterModel.displayed = []
        self.currentTemplate = templateFilePath.split("/")[-1]
        self.ui.displayedFileLabel.setText(templateFilePath.split("/")[-1])
        self.ui.hyperthoughtTemplateLineEdit.setText(templateFilePath)
        self.ui.otherDataFileLineEdit.setText("")
        infile = open(templateFilePath, "r")
        data = infile.readline()
        fileType = infile.readline()
        fileType = json.loads(fileType)
        self.fileType = fileType[0][-4:]
        editables = infile.readline()
        self.editableKeys = json.loads(editables)
        self.usetablemodel.editableKeys = self.editableKeys
        self.toggleButtons()
        self.templatedata = json.loads(data)
        self.usetablemodel.addTemplateList(self.templatedata)
        self.usefilterModel.setFilterRegExp(QRegExp())
        infile.close()

        return True

    def showEvent(self, event):
        super().showEvent(event)
        self.movethedamnbutton()

    def toggleButtons(self):
        if (self.ui.hyperthoughtTemplateLineEdit.text() != ""
                and self.ui.otherDataFileLineEdit.text() != ""
                and self.ui.useTemplateListView.model().rowCount() > 0
                and self.ui.hyperthoughtLocationLineEdit.text() != ""):

            self.ui.hyperthoughtUploadButton.setEnabled(True)

    def uploadToHyperthought(self):
        auth_control = htauthcontroller.HTAuthorizationController(
            self.accessKey)
        metadataJson = ht_utilities.dict_to_ht_metadata(
            self.usefilterModel.displayed)
        progress = QProgressDialog("Uploading files...", "Abort Upload", 0,
                                   len(self.uselistmodel.metadataList), self)

        progress.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint
                                | Qt.WindowTitleHint)
        progress.setAttribute(Qt.WA_DeleteOnClose)
        self.createUpload.emit(self.uselistmodel.metadataList, auth_control,
                               self.folderuuid, metadataJson)
        self.uploader.currentUploadDone.connect(progress.setValue)
        self.uploader.currentlyUploading.connect(progress.setLabelText)
        self.uploader.allUploadsDone.connect(progress.accept)
        progress.canceled.connect(lambda: self.uploader.interruptUpload())
        progress.setFixedSize(500, 100)
        progress.exec()
Ejemplo n.º 18
0
class ObjListWindow(PBDialog):
    """Create a window managing a list (of bibtexs or of experiments)"""
    def __init__(self, parent=None, gridLayout=False):
        """Init using parent class and create common definitions

        Parameters:
            parent: the parent object
            gridLayout (boolean, default False):
                if True, use a QGridLayout, otherwise a QVBoxLayout
        """
        super(ObjListWindow, self).__init__(parent)
        self.tableWidth = None
        self.proxyModel = None
        self.gridLayout = gridLayout
        self.filterInput = None
        self.proxyModel = None
        self.tableview = None
        if gridLayout:
            self.currLayout = QGridLayout()
        else:
            self.currLayout = QVBoxLayout()
        self.setLayout(self.currLayout)

    def triggeredContextMenuEvent(self, row, col, event):
        """Not implemented: requires a subclass"""
        raise NotImplementedError()

    def handleItemEntered(self, index):
        """Not implemented: requires a subclass"""
        raise NotImplementedError()

    def cellClick(self, index):
        """Not implemented: requires a subclass"""
        raise NotImplementedError()

    def cellDoubleClick(self, index):
        """Not implemented: requires a subclass"""
        raise NotImplementedError()

    def createTable(self, *args, **kwargs):
        """Not implemented: requires a subclass"""
        raise NotImplementedError()

    def changeFilter(self, string):
        """Change the filter of the current view.

        Parameter:
            string: the filter string to be matched
        """
        self.proxyModel.setFilterRegExp(str(string))

    def addFilterInput(self, placeholderText, gridPos=(1, 0)):
        """Add a `QLineEdit` to change the filter of the list.

        Parameter:
            placeholderText: the text to be shown
                when no filter is present
            gridPos (tuple): if gridLayout is active,
                the position of the `QLineEdit` in the `QGridLayout`
        """
        self.filterInput = QLineEdit("", self)
        self.filterInput.setPlaceholderText(placeholderText)
        self.filterInput.textChanged.connect(self.changeFilter)

        if self.gridLayout:
            self.currLayout.addWidget(self.filterInput, *gridPos)
        else:
            self.currLayout.addWidget(self.filterInput)
        self.filterInput.setFocus()

    def setProxyStuff(self, sortColumn, sortOrder):
        """Prepare the proxy model to filter and sort the view.

        Parameter:
            sortColumn: the index of the column to use
                for sorting at the beginning
            sortOrder: the order for sorting
                (`Qt.AscendingOrder` or `Qt.DescendingOrder`)
        """
        self.proxyModel = QSortFilterProxyModel(self)
        self.proxyModel.setSourceModel(self.tableModel)
        self.proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.proxyModel.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.proxyModel.setFilterKeyColumn(-1)

        self.tableview = PBTableView(self)
        self.tableview.setModel(self.proxyModel)
        self.tableview.setSortingEnabled(True)
        self.tableview.setMouseTracking(True)
        self.tableview.setSelectionBehavior(QAbstractItemView.SelectRows)
        try:
            self.tableview.sortByColumn(self.tableModel.header.index("bibkey"),
                                        Qt.AscendingOrder)
        except (IndexError, ValueError):
            pass
        self.tableview.sortByColumn(sortColumn, sortOrder)
        try:
            self.proxyModel.sort(self.tableModel.header.index("bibkey"),
                                 Qt.AscendingOrder)
        except (IndexError, ValueError):
            pass
        self.proxyModel.sort(sortColumn, sortOrder)
        self.currLayout.addWidget(self.tableview)

    def finalizeTable(self, gridPos=(1, 0)):
        """Resize the table to fit the contents,
        connect functions, add to layout

        Parameter:
            gridPos (tuple): if gridLayout is active,
            the position of the `QLineEdit` in the `QGridLayout`
        """
        self.tableview.resizeColumnsToContents()

        maxh = QDesktopWidget().availableGeometry().height()
        maxw = QDesktopWidget().availableGeometry().width()
        self.setMaximumHeight(maxh)
        self.setMaximumWidth(maxw)

        hwidth = self.tableview.horizontalHeader().length()
        swidth = self.tableview.style().pixelMetric(QStyle.PM_ScrollBarExtent)
        fwidth = self.tableview.frameWidth() * 2

        if self.tableWidth is None:
            if hwidth > maxw - (swidth + fwidth):
                self.tableWidth = maxw - (swidth + fwidth)
            else:
                self.tableWidth = hwidth + swidth + fwidth
        self.tableview.setFixedWidth(self.tableWidth)

        self.setMinimumHeight(600)

        self.tableview.resizeColumnsToContents()
        self.tableview.resizeRowsToContents()

        self.tableview.entered.connect(self.handleItemEntered)
        self.tableview.clicked.connect(self.cellClick)
        self.tableview.doubleClicked.connect(self.cellDoubleClick)

        if self.gridLayout:
            self.currLayout.addWidget(self.tableview, *gridPos)
        else:
            self.currLayout.addWidget(self.tableview)

    def recreateTable(self):
        """Delete the previous table widget and other layout items,
        then create new ones
        """
        self.cleanLayout()
        self.createTable()
Ejemplo n.º 19
0
class ExtendedComboBox(QComboBox):
    def __init__(self, table_name="", update_field="", database=None, parent=None):
        super(ExtendedComboBox, self).__init__(parent)
        self.__type = Types.TEXT
        self.setMinimumHeight(30)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setEditable(True)
        self._table_name = table_name
        self._update_field = update_field
        
        self._database = database

        # add a filter model to filter matching items
        self.pFilterModel = QSortFilterProxyModel(self)
        self.pFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.pFilterModel.setSourceModel(self.model())

        # add a completer, which uses the filter model
        self.completer = QCompleter(self.pFilterModel, self)
        # always show all (filtered) completions
        self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.setCompleter(self.completer)

        # connect signals
        self.lineEdit().textEdited.connect(self.pFilterModel.setFilterFixedString)
        self.completer.activated.connect(self.on_completer_activated)

    def setDatabase(self, database):
        self._database = database

    def getType(self):
        return self.__type

    # on selection of an item from the completer, select the corresponding item from combobox 
    def on_completer_activated(self, text):
        if text:
            index = self.findText(text)
            self.setCurrentIndex(index)
            self.activated[str].emit(self.itemText(index))

    # on model change, update the models of the filter and completer as well 
    def setModel(self, model):
        super(ExtendedComboBox, self).setModel(model)
        self.pFilterModel.setSourceModel(model)
        self.completer.setModel(self.pFilterModel)

    # on model column change, update the model column of the filter and completer as well
    def setModelColumn(self, column):
        self.completer.setCompletionColumn(column)
        self.pFilterModel.setFilterKeyColumn(column)
        super(ExtendedComboBox, self).setModelColumn(column)    

    def updateListValues(self):
        if self._update_field and self._database != None:
            self.clear()
            self._database.openDatabase()
            items = list(set(self._database.getValuesFromField(self._table_name, self._update_field)))
            self._database.closeDatabase()
            self.addItems(items) 

    def setValue(self, value):
        if self._update_field and self._table_name and self._database != None:
            self.updateListValues()
        index = self.findText(value)
        if index == -1:
            self.setCurrentIndex(0)
        else:
            self.setCurrentIndex(index)

    def getValue(self):
        return self.currentText()
    
    def clearValue(self):
        self.setCurrentIndex(0)
    
    def connectFunction(self, function):
        self.activated.connect(function)