def createMailModel(parent):
    model = QStandardItemModel(0, 3, parent)

    model.setHeaderData(0, Qt.Horizontal, "Subject")
    model.setHeaderData(1, Qt.Horizontal, "Sender")
    model.setHeaderData(2, Qt.Horizontal, "Date")

    addMail(model, "Happy New Year!", "Grace K. <*****@*****.**>",
            QDateTime(QDate(2006, 12, 31), QTime(17, 3)))
    addMail(model, "Radically new concept", "Grace K. <*****@*****.**>",
            QDateTime(QDate(2006, 12, 22), QTime(9, 44)))
    addMail(model, "Accounts", "*****@*****.**",
            QDateTime(QDate(2006, 12, 31), QTime(12, 50)))
    addMail(model, "Expenses", "Joe Bloggs <*****@*****.**>",
            QDateTime(QDate(2006, 12, 25), QTime(11, 39)))
    addMail(model, "Re: Expenses", "Andy <*****@*****.**>",
            QDateTime(QDate(2007, 1, 2), QTime(16, 5)))
    addMail(model, "Re: Accounts", "Joe Bloggs <*****@*****.**>",
            QDateTime(QDate(2007, 1, 3), QTime(14, 18)))
    addMail(model, "Re: Accounts", "Andy <*****@*****.**>",
            QDateTime(QDate(2007, 1, 3), QTime(14, 26)))
    addMail(model, "Sports", "Linda Smith <*****@*****.**>",
            QDateTime(QDate(2007, 1, 5), QTime(11, 33)))
    addMail(model, "AW: Sports", "Rolf Newschweinstein <*****@*****.**>",
            QDateTime(QDate(2007, 1, 5), QTime(12, 0)))
    addMail(model, "RE: Sports", "Petra Schmidt <*****@*****.**>",
            QDateTime(QDate(2007, 1, 5), QTime(12, 1)))

    return model
Exemplo n.º 2
0
 def onRangeChange(self, index):
     item = self.range_combo.itemData(index)
     self._begin, self._end = self.report_ranges[item][ITEM_METHOD]()
     self.changing_range = True
     self.from_date.setDateTime(QDateTime.fromSecsSinceEpoch(self._begin, spec=Qt.UTC))
     self.to_date.setDateTime(QDateTime.fromSecsSinceEpoch(self._end, spec=Qt.UTC))
     self.changing_range = False
     self.changed.emit(self._begin, self._end)
Exemplo n.º 3
0
    def __init__(self, parent, quotes, trades, data_range, currency_name):
        QWidget.__init__(self, parent)
        self.setMinimumWidth(600)
        self.setMinimumHeight(400)

        self.quotes_series = QLineSeries()
        for point in quotes:  # Conversion to 'float' in order not to get 'int' overflow on some platforms
            self.quotes_series.append(float(point['timestamp']),
                                      point['quote'])

        self.trade_series = QScatterSeries()
        for point in trades:  # Conversion to 'float' in order not to get 'int' overflow on some platforms
            self.trade_series.append(float(point['timestamp']), point['price'])
        self.trade_series.setMarkerSize(5)
        self.trade_series.setBorderColor(CustomColor.LightRed)
        self.trade_series.setBrush(CustomColor.DarkRed)

        axisX = QDateTimeAxis()
        axisX.setTickCount(11)
        axisX.setRange(QDateTime().fromSecsSinceEpoch(data_range[0]),
                       QDateTime().fromSecsSinceEpoch(data_range[1]))
        axisX.setFormat("yyyy/MM/dd")
        axisX.setLabelsAngle(-90)
        axisX.setTitleText("Date")

        axisY = QValueAxis()
        axisY.setTickCount(11)
        axisY.setRange(data_range[2], data_range[3])
        axisY.setTitleText("Price, " + currency_name)

        self.chartView = QChartView()
        self.chartView.chart().addSeries(self.quotes_series)
        self.chartView.chart().addSeries(self.trade_series)
        self.chartView.chart().addAxis(axisX, Qt.AlignBottom)
        self.chartView.chart().setAxisX(axisX, self.quotes_series)
        self.chartView.chart().setAxisX(axisX, self.trade_series)
        self.chartView.chart().addAxis(axisY, Qt.AlignLeft)
        self.chartView.chart().setAxisY(axisY, self.quotes_series)
        self.chartView.chart().setAxisY(axisY, self.trade_series)
        self.chartView.chart().legend().hide()
        self.chartView.setViewportMargins(0, 0, 0, 0)
        self.chartView.chart().layout().setContentsMargins(
            0, 0, 0, 0)  # To remove extra spacing around chart
        self.chartView.chart().setBackgroundRoundness(
            0)  # To remove corner rounding
        self.chartView.chart().setMargins(QMargins(
            0, 0, 0, 0))  # Allow chart to fill all space

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0,
                                       0)  # Remove extra space around layout
        self.layout.addWidget(self.chartView)
        self.setLayout(self.layout)
Exemplo n.º 4
0
 def onReportRangeChange(self, range_index):
     report_ranges = {
         0: lambda: (0, 0),
         1: ManipulateDate.Last3Months,
         2: ManipulateDate.RangeYTD,
         3: ManipulateDate.RangeThisYear,
         4: ManipulateDate.RangePreviousYear
     }
     begin, end = report_ranges[range_index]()
     self.ReportFromDate.setDateTime(
         QDateTime.fromSecsSinceEpoch(begin, spec=Qt.UTC))
     self.ReportToDate.setDateTime(
         QDateTime.fromSecsSinceEpoch(end, spec=Qt.UTC))
Exemplo n.º 5
0
 def showTime(self):
     # 获取系统现在的时间
     time = QDateTime.currentDateTime()
     # 设置系统时间显示格式
     timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd")
     # 在标签上显示时间
     self.label.setText(timeDisplay)
Exemplo n.º 6
0
 def from_string(self, text, original_value):
     if isinstance(original_value, QColor):
         match = self.color_exp.match(text)
         return QColor(min(int(match.captured(1)), 255),
                       min(int(match.captured(2)), 255),
                       min(int(match.captured(3)), 255),
                       min(int(match.captured(4)), 255))
     if isinstance(original_value, QDate):
         value = QDate.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QDateTime):
         value = QDateTime.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QTime):
         value = QTime.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QPoint):
         match = self.point_exp.match(text)
         return QPoint(int(match.captured(1)),
                       int(match.captured(2)))
     if isinstance(original_value, QRect):
         match = self.rect_exp.match(text)
         return QRect(int(match.captured(1)),
                      int(match.captured(2)),
                      int(match.captured(3)),
                      int(match.captured(4)))
     if isinstance(original_value, QSize):
         match = self.size_exp.match(text)
         return QSize(int(match.captured(1)),
                      int(match.captured(2)))
     if isinstance(original_value, list):
         return text.split(',')
     return type(original_value)(text)
Exemplo n.º 7
0
 def setEditorData(self, editor, index):
     if index.column() == self._key:
         editor.setCurrentIndex(
             editor.findData(index.model().data(index, Qt.EditRole)))
     elif index.column() == self._value:
         type_idx = index.model().data(index.sibling(
             index.row(), self._key),
                                       role=Qt.EditRole)
         if self.types[type_idx][1] == "str":
             editor.setText(index.model().data(index, Qt.EditRole))
         elif self.types[type_idx][1] == "date":
             try:
                 timestamp = int(index.model().data(index, Qt.EditRole))
                 editor.setDateTime(
                     QDateTime.fromSecsSinceEpoch(timestamp, spec=Qt.UTC))
             except ValueError:
                 QStyledItemDelegate.setEditorData(self, editor, index)
         elif self.types[type_idx][1] == "float":
             try:
                 amount = float(index.model().data(index, Qt.EditRole))
             except (ValueError, TypeError):
                 amount = 0.0
             # QLocale().toString works in a bit weird way with float formatting - garbage appears after 5-6 decimal digits
             # if too long precision is specified for short number. So we need to be more precise setting precision.
             decimal_places = -decimal.Decimal(
                 str(amount).rstrip('0')).as_tuple().exponent
             editor.setText(QLocale().toString(amount, 'f', decimal_places))
         else:
             assert False, f"Unknown data type '{self.types[type_idx][1]}' in DataDelegate.setEditorData()"
     else:
         assert False, f"Delegate DataDelegate.setEditorData() called for not-initialized column {index.column()}"
Exemplo n.º 8
0
 def setEditorData(self, editor, index):
     timestamp = index.model().data(index, Qt.EditRole)
     if timestamp == '':
         QStyledItemDelegate.setEditorData(self, editor, index)
     else:
         editor.setDateTime(
             QDateTime.fromSecsSinceEpoch(timestamp, spec=Qt.UTC))
Exemplo n.º 9
0
    def __init__(self, parent=None):
        MdiWidget.__init__(self, parent)
        self.setupUi(self)

        self.current_index = None  # this is used in onOperationContextMenu() to track item for menu

        # Set icons
        self.NewOperationBtn.setIcon(load_icon("new.png"))
        self.CopyOperationBtn.setIcon(load_icon("copy.png"))
        self.DeleteOperationBtn.setIcon(load_icon("delete.png"))

        # Operations view context menu
        self.contextMenu = QMenu(self.OperationsTableView)
        self.actionReconcile = QAction(load_icon("reconcile.png"),
                                       self.tr("Reconcile"), self)
        self.actionCopy = QAction(load_icon("copy.png"), self.tr("Copy"), self)
        self.actionDelete = QAction(load_icon("delete.png"), self.tr("Delete"),
                                    self)
        self.contextMenu.addAction(self.actionReconcile)
        self.contextMenu.addSeparator()
        self.contextMenu.addAction(self.actionCopy)
        self.contextMenu.addAction(self.actionDelete)

        # Customize UI configuration
        self.balances_model = BalancesModel(self.BalancesTableView)
        self.BalancesTableView.setModel(self.balances_model)
        self.balances_model.configureView()

        self.operations_model = OperationsModel(self.OperationsTableView)
        self.OperationsTableView.setModel(self.operations_model)
        self.operations_model.configureView()
        self.OperationsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.connect_signals_and_slots()

        self.NewOperationMenu = QMenu()
        for i in range(self.OperationsTabs.count()):
            if hasattr(self.OperationsTabs.widget(i), "isCustom"):
                self.OperationsTabs.widget(i).dbUpdated.connect(self.dbUpdated)
                self.OperationsTabs.widget(i).dbUpdated.connect(
                    self.operations_model.refresh)
                self.NewOperationMenu.addAction(
                    self.OperationsTabs.widget(i).name,
                    partial(self.createOperation, i))
        self.NewOperationBtn.setMenu(self.NewOperationMenu)

        # Setup balance and holdings parameters
        current_time = QDateTime.currentDateTime()
        current_time.setTimeSpec(
            Qt.UTC)  # We use UTC everywhere so need to force TZ info
        self.BalanceDate.setDateTime(current_time)
        self.BalancesCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))

        self.OperationsTabs.setCurrentIndex(LedgerTransaction.NA)
        self.OperationsTableView.selectRow(0)
        self.DateRange.setCurrentIndex(0)
Exemplo n.º 10
0
Arquivo: main.py Projeto: KDAB/KDChart
    def __init__(self, parent=None):
        super(MyTaskModel, self).__init__(parent)
        self.m_tasks = []

        for i in range(0, 6, 2):
            task = self.Task()
            task.title = "Item " + str(len(self.m_tasks) + 1)
            task.start = QDateTime.currentDateTime().addDays(i)
            task.end = task.start.addDays(1)
            self.m_tasks.append(task)
Exemplo n.º 11
0
    def setupUi(self, HoldingsWidget):
        if not HoldingsWidget.objectName():
            HoldingsWidget.setObjectName(u"HoldingsWidget")
        HoldingsWidget.resize(1066, 589)
        self.verticalLayout = QVBoxLayout(HoldingsWidget)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.HoldingsParamsFrame = QFrame(HoldingsWidget)
        self.HoldingsParamsFrame.setObjectName(u"HoldingsParamsFrame")
        self.HoldingsParamsFrame.setFrameShape(QFrame.Panel)
        self.HoldingsParamsFrame.setFrameShadow(QFrame.Sunken)
        self.horizontalLayout_8 = QHBoxLayout(self.HoldingsParamsFrame)
        self.horizontalLayout_8.setSpacing(6)
        self.horizontalLayout_8.setObjectName(u"horizontalLayout_8")
        self.horizontalLayout_8.setContentsMargins(2, 2, 2, 2)
        self.HoldingsDate = QDateEdit(self.HoldingsParamsFrame)
        self.HoldingsDate.setObjectName(u"HoldingsDate")
        self.HoldingsDate.setDateTime(
            QDateTime(QDate(2020, 11, 24), QTime(21, 0, 0)))
        self.HoldingsDate.setCalendarPopup(True)
        self.HoldingsDate.setTimeSpec(Qt.UTC)

        self.horizontalLayout_8.addWidget(self.HoldingsDate)

        self.HoldingsCurrencyLbl = QLabel(self.HoldingsParamsFrame)
        self.HoldingsCurrencyLbl.setObjectName(u"HoldingsCurrencyLbl")

        self.horizontalLayout_8.addWidget(self.HoldingsCurrencyLbl)

        self.HoldingsCurrencyCombo = CurrencyComboBox(self.HoldingsParamsFrame)
        self.HoldingsCurrencyCombo.setObjectName(u"HoldingsCurrencyCombo")

        self.horizontalLayout_8.addWidget(self.HoldingsCurrencyCombo)

        self.horizontalSpacer = QSpacerItem(1411, 20, QSizePolicy.Expanding,
                                            QSizePolicy.Minimum)

        self.horizontalLayout_8.addItem(self.horizontalSpacer)

        self.verticalLayout.addWidget(self.HoldingsParamsFrame)

        self.HoldingsTableView = QTreeView(HoldingsWidget)
        self.HoldingsTableView.setObjectName(u"HoldingsTableView")
        self.HoldingsTableView.setFrameShape(QFrame.Panel)
        self.HoldingsTableView.setAlternatingRowColors(True)
        self.HoldingsTableView.setAnimated(True)
        self.HoldingsTableView.setAllColumnsShowFocus(True)

        self.verticalLayout.addWidget(self.HoldingsTableView)

        self.retranslateUi(HoldingsWidget)

        QMetaObject.connectSlotsByName(HoldingsWidget)
Exemplo n.º 12
0
    def init(self):
        self.ui.type.addItem("Event", KDGantt.TypeEvent)
        self.ui.type.addItem("Task", KDGantt.TypeTask)
        self.ui.type.addItem("Summary", KDGantt.TypeSummary)
        self.ui.type.addItem("Multi", KDGantt.TypeMulti)

        for row in range(0, self.model.rowCount()):
            self.addDependItem(self.model, self.model.index(row, 0))

        self.ui.startDate.dateTimeChanged.connect(self.updateEndDate)
        self.ui.readOnly.toggled.connect(self.disableEditing)
        self.ui.startDate.setDateTime(QDateTime.currentDateTime())
Exemplo n.º 13
0
 def post_history(
         self,
         date_time: QDateTime = QDateTime()
 ) -> None:
     # this method is called as Slot by ClickableLabel.mouseReleaseEvent() without arguments
     # this method is called directly by EvelynDesktop.report_done() with a date_time
     if self.state_key is None:
         return
     logging.info('Post history ...')
     self.label_alert.setText('Sending ...')
     self.label_alert.setStyleSheet(f'background: #dddddd;')
     self.setCurrentWidget(self.label_alert)
     self.signal_post_history.emit(self.state_key, date_time)
Exemplo n.º 14
0
    def addDemoEntry(self):
        softwareRelease = MyStandardItem("Software Release")
        codeFreeze = MyStandardItem("Code Freeze")
        codeFreeze.setData(KDGantt.TextPositionRole,
                           StyleOptionGanttItem.Right)
        packaging = MyStandardItem("Packaging")
        upload = MyStandardItem("Upload")
        testing = MyStandardItem("Testing")
        updateDocumentation = MyStandardItem("Update Documentation")

        now = QDateTime.currentDateTime()
        softwareRelease.appendRow([
            codeFreeze,
            MyStandardItem(KDGantt.TypeEvent),
            MyStandardItem(now, KDGantt.StartTimeRole)
        ])
        softwareRelease.appendRow([
            packaging,
            MyStandardItem(KDGantt.TypeTask),
            MyStandardItem(now.addDays(5), KDGantt.StartTimeRole),
            MyStandardItem(now.addDays(10), KDGantt.EndTimeRole)
        ])
        softwareRelease.appendRow([
            upload,
            MyStandardItem(KDGantt.TypeTask),
            MyStandardItem(
                now.addDays(10).addSecs(2 * 60 * 60), KDGantt.StartTimeRole),
            MyStandardItem(now.addDays(11), KDGantt.EndTimeRole)
        ])
        softwareRelease.appendRow([
            testing,
            MyStandardItem(KDGantt.TypeTask),
            MyStandardItem(now.addSecs(3 * 60 * 60), KDGantt.StartTimeRole),
            MyStandardItem(now.addDays(5), KDGantt.EndTimeRole)
        ])
        softwareRelease.appendRow([
            updateDocumentation,
            MyStandardItem(KDGantt.TypeTask),
            MyStandardItem(now.addSecs(3 * 60 * 60), KDGantt.StartTimeRole),
            MyStandardItem(now.addDays(3), KDGantt.EndTimeRole)
        ])
        self.model.appendRow(
            [softwareRelease,
             MyStandardItem(KDGantt.TypeSummary)])
        self.addConstraintFromItem(codeFreeze, packaging)
        self.addConstraintFromItem(codeFreeze, testing)
        self.addConstraintFromItem(codeFreeze, updateDocumentation)
        self.addConstraintFromItem(packaging, upload)
        self.addConstraintFromItem(testing, packaging)
        self.addConstraintFromItem(updateDocumentation, packaging)
Exemplo n.º 15
0
 def post_history(
         self,
         key: int,
         date_time: QDateTime
 ) -> None:
     try:
         data = self.client.post_history(
             guild=self.guild, member=self.member, key=key,
             time_utc=date_time.toPython() if date_time else None)
         text = str(data['message'])
         error = False
     except Exception as e:
         text = str(e)
         error = True
     self.signal_post_history_done.emit(text, error)
Exemplo n.º 16
0
 def __init__(
         self,
         parent: QWidget
 ) -> None:
     super().__init__(parent)
     self.date_time_edit = QDateTimeEdit()
     self.date_time_edit.setDateTime(QDateTime.currentDateTime())
     self.button_box = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel)
     self.button_box.accepted.connect(self.accept)
     self.button_box.rejected.connect(self.reject)
     self.main_layout = QVBoxLayout()
     self.main_layout.addWidget(self.date_time_edit)
     self.main_layout.addWidget(self.button_box)
     self.setLayout(self.main_layout)
     self.setWindowTitle('Report done')
    def create_simple_inputwidgets_groupbox(self):
        result = QGroupBox("Simple Input Widgets")
        init_widget(result, "bottomRightGroupBox")
        result.setCheckable(True)
        result.setChecked(True)

        lineedit = QLineEdit("s3cRe7")
        init_widget(lineedit, "lineEdit")
        lineedit.setClearButtonEnabled(True)
        lineedit.setEchoMode(QLineEdit.Password)

        spin_box = QSpinBox()
        init_widget(spin_box, "spinBox")
        spin_box.setValue(50)

        date_timeedit = QDateTimeEdit()
        init_widget(date_timeedit, "dateTimeEdit")
        date_timeedit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider()
        init_widget(slider, "slider")
        slider.setOrientation(Qt.Horizontal)
        slider.setValue(40)

        scrollbar = QScrollBar()
        init_widget(scrollbar, "scrollBar")
        scrollbar.setOrientation(Qt.Horizontal)
        scrollbar.setValue(60)

        dial = QDial()
        init_widget(dial, "dial")
        dial.setValue(30)
        dial.setNotchesVisible(True)

        layout = QGridLayout(result)
        layout.addWidget(lineedit, 0, 0, 1, 2)
        layout.addWidget(spin_box, 1, 0, 1, 2)
        layout.addWidget(date_timeedit, 2, 0, 1, 2)
        layout.addWidget(slider, 3, 0)
        layout.addWidget(scrollbar, 4, 0)
        layout.addWidget(dial, 3, 1, 2, 1)
        layout.setRowStretch(5, 1)
        return result
Exemplo n.º 18
0
    def __init__(self, parent=None):
        MdiWidget.__init__(self, parent)
        self.setupUi(self)
        self.parent_mdi = parent

        self.holdings_model = HoldingsModel(self.HoldingsTableView)
        self.HoldingsTableView.setModel(self.holdings_model)
        self.holdings_model.configureView()
        self.HoldingsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.connect_signals_and_slots()

        # Setup holdings parameters
        current_time = QDateTime.currentDateTime()
        current_time.setTimeSpec(
            Qt.UTC)  # We use UTC everywhere so need to force TZ info
        self.HoldingsDate.setDateTime(current_time)
        self.HoldingsCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))
Exemplo n.º 19
0
    def parseQRdata(self, qr_data):
        self.QR_data = qr_data

        logging.info(self.tr("QR: " + self.QR_data))
        params = parse_qs(self.QR_data)
        try:
            for timestamp_pattern in self.timestamp_patterns:
                datetime = QDateTime.fromString(params['t'][0], timestamp_pattern)
                datetime.setTimeSpec(Qt.UTC)
                if datetime.isValid():
                    self.SlipTimstamp.setDateTime(datetime)
            self.SlipAmount.setText(params['s'][0])
            self.FN.setText(params['fn'][0])
            self.FD.setText(params['i'][0])
            self.FP.setText(params['fp'][0])
            self.SlipType.setCurrentIndex(int(params['n'][0]) - 1)
        except KeyError:
            logging.warning(self.tr("QR available but pattern isn't recognized: " + self.QR_data))
            return
        self.qr_data_validated.emit()
Exemplo n.º 20
0
    def setupUi(self, OperationsWidget):
        if not OperationsWidget.objectName():
            OperationsWidget.setObjectName(u"OperationsWidget")
        OperationsWidget.resize(1232, 552)
        self.verticalLayout_4 = QVBoxLayout(OperationsWidget)
        self.verticalLayout_4.setSpacing(0)
        self.verticalLayout_4.setObjectName(u"verticalLayout_4")
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.BalanceOperationsSplitter = QSplitter(OperationsWidget)
        self.BalanceOperationsSplitter.setObjectName(
            u"BalanceOperationsSplitter")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.BalanceOperationsSplitter.sizePolicy().hasHeightForWidth())
        self.BalanceOperationsSplitter.setSizePolicy(sizePolicy)
        self.BalanceOperationsSplitter.setOrientation(Qt.Horizontal)
        self.BalanceBox = QGroupBox(self.BalanceOperationsSplitter)
        self.BalanceBox.setObjectName(u"BalanceBox")
        sizePolicy1 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy1.setHorizontalStretch(1)
        sizePolicy1.setVerticalStretch(0)
        sizePolicy1.setHeightForWidth(
            self.BalanceBox.sizePolicy().hasHeightForWidth())
        self.BalanceBox.setSizePolicy(sizePolicy1)
        self.BalanceBox.setMaximumSize(QSize(16777215, 16777215))
        self.verticalLayout = QVBoxLayout(self.BalanceBox)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.BalanceConfigFrame = QFrame(self.BalanceBox)
        self.BalanceConfigFrame.setObjectName(u"BalanceConfigFrame")
        self.BalanceConfigFrame.setMinimumSize(QSize(408, 0))
        self.BalanceConfigFrame.setMaximumSize(QSize(16777215, 44))
        self.BalanceConfigFrame.setFrameShape(QFrame.Panel)
        self.BalanceConfigFrame.setFrameShadow(QFrame.Plain)
        self.BalanceConfigFrame.setLineWidth(0)
        self.horizontalLayout_2 = QHBoxLayout(self.BalanceConfigFrame)
        self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
        self.horizontalLayout_2.setContentsMargins(2, 2, 2, 2)
        self.BalanceDate = QDateEdit(self.BalanceConfigFrame)
        self.BalanceDate.setObjectName(u"BalanceDate")
        self.BalanceDate.setDateTime(
            QDateTime(QDate(2020, 11, 25), QTime(21, 0, 0)))
        self.BalanceDate.setCalendarPopup(True)
        self.BalanceDate.setTimeSpec(Qt.UTC)

        self.horizontalLayout_2.addWidget(self.BalanceDate)

        self.CurrencyLbl = QLabel(self.BalanceConfigFrame)
        self.CurrencyLbl.setObjectName(u"CurrencyLbl")
        self.CurrencyLbl.setLayoutDirection(Qt.LeftToRight)
        self.CurrencyLbl.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                      | Qt.AlignVCenter)

        self.horizontalLayout_2.addWidget(self.CurrencyLbl)

        self.BalancesCurrencyCombo = CurrencyComboBox(self.BalanceConfigFrame)
        self.BalancesCurrencyCombo.setObjectName(u"BalancesCurrencyCombo")

        self.horizontalLayout_2.addWidget(self.BalancesCurrencyCombo)

        self.ShowInactiveCheckBox = QCheckBox(self.BalanceConfigFrame)
        self.ShowInactiveCheckBox.setObjectName(u"ShowInactiveCheckBox")

        self.horizontalLayout_2.addWidget(self.ShowInactiveCheckBox)

        self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_2.addItem(self.horizontalSpacer_2)

        self.verticalLayout.addWidget(self.BalanceConfigFrame)

        self.BalancesTableView = QTableView(self.BalanceBox)
        self.BalancesTableView.setObjectName(u"BalancesTableView")
        self.BalancesTableView.setFrameShape(QFrame.Panel)
        self.BalancesTableView.setEditTriggers(
            QAbstractItemView.EditKeyPressed
            | QAbstractItemView.SelectedClicked)
        self.BalancesTableView.setAlternatingRowColors(True)
        self.BalancesTableView.setSelectionMode(QAbstractItemView.NoSelection)
        self.BalancesTableView.setGridStyle(Qt.DotLine)
        self.BalancesTableView.setWordWrap(False)
        self.BalancesTableView.verticalHeader().setVisible(False)
        self.BalancesTableView.verticalHeader().setMinimumSectionSize(20)
        self.BalancesTableView.verticalHeader().setDefaultSectionSize(20)

        self.verticalLayout.addWidget(self.BalancesTableView)

        self.BalanceOperationsSplitter.addWidget(self.BalanceBox)
        self.OperationsBox = QGroupBox(self.BalanceOperationsSplitter)
        self.OperationsBox.setObjectName(u"OperationsBox")
        sizePolicy2 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy2.setHorizontalStretch(4)
        sizePolicy2.setVerticalStretch(0)
        sizePolicy2.setHeightForWidth(
            self.OperationsBox.sizePolicy().hasHeightForWidth())
        self.OperationsBox.setSizePolicy(sizePolicy2)
        self.OperationsBox.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.verticalLayout_2 = QVBoxLayout(self.OperationsBox)
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.OperationConfigFrame = QFrame(self.OperationsBox)
        self.OperationConfigFrame.setObjectName(u"OperationConfigFrame")
        self.OperationConfigFrame.setEnabled(True)
        self.OperationConfigFrame.setMinimumSize(QSize(0, 0))
        self.OperationConfigFrame.setFrameShape(QFrame.Panel)
        self.OperationConfigFrame.setFrameShadow(QFrame.Plain)
        self.OperationConfigFrame.setLineWidth(0)
        self.horizontalLayout_3 = QHBoxLayout(self.OperationConfigFrame)
        self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
        self.horizontalLayout_3.setContentsMargins(2, 2, 2, 2)
        self.DateRange = DateRangeSelector(self.OperationConfigFrame)
        self.DateRange.setObjectName(u"DateRange")
        self.DateRange.setProperty("ItemsList", u"week;month;quarter;year;all")

        self.horizontalLayout_3.addWidget(self.DateRange)

        self.AccountLbl = QLabel(self.OperationConfigFrame)
        self.AccountLbl.setObjectName(u"AccountLbl")

        self.horizontalLayout_3.addWidget(self.AccountLbl)

        self.ChooseAccountBtn = AccountButton(self.OperationConfigFrame)
        self.ChooseAccountBtn.setObjectName(u"ChooseAccountBtn")

        self.horizontalLayout_3.addWidget(self.ChooseAccountBtn)

        self.SearchLbl = QLabel(self.OperationConfigFrame)
        self.SearchLbl.setObjectName(u"SearchLbl")

        self.horizontalLayout_3.addWidget(self.SearchLbl)

        self.SearchString = QLineEdit(self.OperationConfigFrame)
        self.SearchString.setObjectName(u"SearchString")

        self.horizontalLayout_3.addWidget(self.SearchString)

        self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                            QSizePolicy.Minimum)

        self.horizontalLayout_3.addItem(self.horizontalSpacer)

        self.verticalLayout_2.addWidget(self.OperationConfigFrame)

        self.OperationsDetailsSplitter = QSplitter(self.OperationsBox)
        self.OperationsDetailsSplitter.setObjectName(
            u"OperationsDetailsSplitter")
        self.OperationsDetailsSplitter.setOrientation(Qt.Vertical)
        self.OperationsTableView = QTableView(self.OperationsDetailsSplitter)
        self.OperationsTableView.setObjectName(u"OperationsTableView")
        sizePolicy3 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy3.setHorizontalStretch(0)
        sizePolicy3.setVerticalStretch(4)
        sizePolicy3.setHeightForWidth(
            self.OperationsTableView.sizePolicy().hasHeightForWidth())
        self.OperationsTableView.setSizePolicy(sizePolicy3)
        self.OperationsTableView.setAlternatingRowColors(True)
        self.OperationsTableView.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.OperationsTableView.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.OperationsTableView.setWordWrap(False)
        self.OperationsDetailsSplitter.addWidget(self.OperationsTableView)
        self.OperationsTableView.verticalHeader().setVisible(False)
        self.OperationsTableView.verticalHeader().setMinimumSectionSize(20)
        self.OperationsTableView.verticalHeader().setDefaultSectionSize(20)
        self.OperationDetails = QFrame(self.OperationsDetailsSplitter)
        self.OperationDetails.setObjectName(u"OperationDetails")
        sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy4.setHorizontalStretch(0)
        sizePolicy4.setVerticalStretch(1)
        sizePolicy4.setHeightForWidth(
            self.OperationDetails.sizePolicy().hasHeightForWidth())
        self.OperationDetails.setSizePolicy(sizePolicy4)
        self.OperationDetails.setMinimumSize(QSize(0, 100))
        self.OperationDetails.setMaximumSize(QSize(16777215, 300))
        self.OperationDetails.setFrameShape(QFrame.Panel)
        self.OperationDetails.setFrameShadow(QFrame.Sunken)
        self.OperationDetails.setLineWidth(1)
        self.horizontalLayout_4 = QHBoxLayout(self.OperationDetails)
        self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
        self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.OperationsTabs = QStackedWidget(self.OperationDetails)
        self.OperationsTabs.setObjectName(u"OperationsTabs")
        self.NoOperation = QWidget()
        self.NoOperation.setObjectName(u"NoOperation")
        self.OperationsTabs.addWidget(self.NoOperation)
        self.IncomeSpending = IncomeSpendingWidget()
        self.IncomeSpending.setObjectName(u"IncomeSpending")
        self.OperationsTabs.addWidget(self.IncomeSpending)
        self.Dividend = DividendWidget()
        self.Dividend.setObjectName(u"Dividend")
        self.OperationsTabs.addWidget(self.Dividend)
        self.Trade = TradeWidget()
        self.Trade.setObjectName(u"Trade")
        self.OperationsTabs.addWidget(self.Trade)
        self.Transfer = TransferWidget()
        self.Transfer.setObjectName(u"Transfer")
        self.OperationsTabs.addWidget(self.Transfer)
        self.CorporateAction = CorporateActionWidget()
        self.CorporateAction.setObjectName(u"CorporateAction")
        self.OperationsTabs.addWidget(self.CorporateAction)

        self.horizontalLayout_4.addWidget(self.OperationsTabs)

        self.OperationsButtons = QFrame(self.OperationDetails)
        self.OperationsButtons.setObjectName(u"OperationsButtons")
        self.verticalLayout_3 = QVBoxLayout(self.OperationsButtons)
        self.verticalLayout_3.setSpacing(2)
        self.verticalLayout_3.setObjectName(u"verticalLayout_3")
        self.verticalLayout_3.setContentsMargins(2, 2, 2, 2)
        self.NewOperationBtn = QPushButton(self.OperationsButtons)
        self.NewOperationBtn.setObjectName(u"NewOperationBtn")

        self.verticalLayout_3.addWidget(self.NewOperationBtn)

        self.CopyOperationBtn = QPushButton(self.OperationsButtons)
        self.CopyOperationBtn.setObjectName(u"CopyOperationBtn")

        self.verticalLayout_3.addWidget(self.CopyOperationBtn)

        self.DeleteOperationBtn = QPushButton(self.OperationsButtons)
        self.DeleteOperationBtn.setObjectName(u"DeleteOperationBtn")

        self.verticalLayout_3.addWidget(self.DeleteOperationBtn)

        self.verticalSpacer_4 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                            QSizePolicy.Expanding)

        self.verticalLayout_3.addItem(self.verticalSpacer_4)

        self.horizontalLayout_4.addWidget(self.OperationsButtons)

        self.OperationsDetailsSplitter.addWidget(self.OperationDetails)

        self.verticalLayout_2.addWidget(self.OperationsDetailsSplitter)

        self.BalanceOperationsSplitter.addWidget(self.OperationsBox)

        self.verticalLayout_4.addWidget(self.BalanceOperationsSplitter)

        self.retranslateUi(OperationsWidget)

        self.OperationsTabs.setCurrentIndex(5)

        QMetaObject.connectSlotsByName(OperationsWidget)
Exemplo n.º 21
0
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)

        self.view = View()
        self.grid = DateTimeGrid()
        self.slider = QSlider(self)
        self.model = QStandardItemModel(self)
        self.cmodel = ConstraintModel()

        ## proxyModel.setSourceModel( &model );
        for i in range(0, 10):
            item = MyStandardItem("Multi Item " + str(i))
            for j in range(0, 20, 3):
                item.appendRow([
                    MyStandardItem("Item " + str(j)),
                    MyStandardItem(KDGantt.TypeTask),
                    MyStandardItem(QDateTime.currentDateTime().addDays(j),
                                   KDGantt.StartTimeRole),
                    MyStandardItem(
                        QDateTime.currentDateTime().addDays(j + 1 + i / 7),
                        KDGantt.EndTimeRole),
                    MyStandardItem(50)
                ])

            item.appendRow([
                MyStandardItem("Event"),
                MyStandardItem(KDGantt.TypeEvent),
                MyStandardItem(QDateTime.currentDateTime(),
                               KDGantt.StartTimeRole),
                MyStandardItem(QDateTime(), KDGantt.EndTimeRole),
                MyStandardItem("")
            ])

            self.model.appendRow([
                item,
                MyStandardItem(KDGantt.TypeMulti),
                MyStandardItem(""),
                MyStandardItem(""),
                MyStandardItem("")
            ])

        pidx = self.model.index(0, 0)
        pidx = self.model.index(0, 0, pidx)
        self.cmodel.addConstraint(
            Constraint(self.model.index(0, 0, pidx),
                       self.model.index(1, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(1, 0, pidx),
                       self.model.index(0, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(1, 0, pidx),
                       self.model.index(10, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(3, 0, pidx),
                       self.model.index(5, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(7, 0, pidx),
                       self.model.index(4, 0, pidx)))

        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setRange(1, 1000)
        self.slider.setValue(100)
        l = QVBoxLayout(self)
        l.addWidget(self.view)
        l.addWidget(self.slider)
        self.grid.setStartDateTime(QDateTime.currentDateTime().addDays(-3))
        self.grid.setDayWidth(100)
        self.grid.setFreeDays([Qt.Saturday, Qt.Sunday])
        self.grid.setFreeDaysBrush(QBrush(Qt.red))

        lv = MyListView(self)
        self.view.setLeftView(lv)
        self.view.setRowController(
            ListViewRowController(lv, self.view.ganttProxyModel()))
        self.view.setGrid(self.grid)
        self.view.setModel(self.model)
        ##view.setConstraintModel( &cmodel );
        self.slider.valueChanged.connect(self.slotZoom)
Exemplo n.º 22
0
Arquivo: main.py Projeto: KDAB/KDChart
 def __init__(self):
     self.title = ""
     self.start = QDateTime()
     self.end = QDateTime()
Exemplo n.º 23
0
    def __init__(self, language):
        QMainWindow.__init__(self, None)
        self.setupUi(self)

        self.currentLanguage = language
        self.current_index = None  # this is used in onOperationContextMenu() to track item for menu

        self.ledger = Ledger()
        self.downloader = QuoteDownloader()
        self.taxes = TaxesRus()
        self.statements = StatementLoader()
        self.backup = JalBackup(self, get_dbfilename(get_app_path()))
        self.estimator = None
        self.price_chart = None

        self.actionImportSlipRU.setEnabled(
            dependency_present(['pyzbar', 'PIL']))

        self.actionAbout = QAction(text=self.tr("About"), parent=self)
        self.MainMenu.addAction(self.actionAbout)

        self.langGroup = QActionGroup(self.menuLanguage)
        self.createLanguageMenu()

        self.statementGroup = QActionGroup(self.menuStatement)
        self.createStatementsImportMenu()

        # Set icons
        self.setWindowIcon(load_icon("jal.png"))
        self.NewOperationBtn.setIcon(load_icon("new.png"))
        self.CopyOperationBtn.setIcon(load_icon("copy.png"))
        self.DeleteOperationBtn.setIcon(load_icon("delete.png"))

        # Operations view context menu
        self.contextMenu = QMenu(self.OperationsTableView)
        self.actionReconcile = QAction(load_icon("reconcile.png"),
                                       self.tr("Reconcile"), self)
        self.actionCopy = QAction(load_icon("copy.png"), self.tr("Copy"), self)
        self.actionDelete = QAction(load_icon("delete.png"), self.tr("Delete"),
                                    self)
        self.contextMenu.addAction(self.actionReconcile)
        self.contextMenu.addSeparator()
        self.contextMenu.addAction(self.actionCopy)
        self.contextMenu.addAction(self.actionDelete)

        # Customize Status bar and logs
        self.ProgressBar = QProgressBar(self)
        self.StatusBar.addWidget(self.ProgressBar)
        self.ProgressBar.setVisible(False)
        self.ledger.setProgressBar(self, self.ProgressBar)
        self.NewLogEventLbl = QLabel(self)
        self.StatusBar.addWidget(self.NewLogEventLbl)
        self.Logs.setNotificationLabel(self.NewLogEventLbl)
        self.Logs.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        self.logger = logging.getLogger()
        self.logger.addHandler(self.Logs)
        log_level = os.environ.get('LOGLEVEL', 'INFO').upper()
        self.logger.setLevel(log_level)

        # Setup reports tab
        self.reports = Reports(self.ReportTableView, self.ReportTreeView)

        # Customize UI configuration
        self.balances_model = BalancesModel(self.BalancesTableView)
        self.BalancesTableView.setModel(self.balances_model)
        self.balances_model.configureView()

        self.holdings_model = HoldingsModel(self.HoldingsTableView)
        self.HoldingsTableView.setModel(self.holdings_model)
        self.holdings_model.configureView()
        self.HoldingsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.operations_model = OperationsModel(self.OperationsTableView)
        self.OperationsTableView.setModel(self.operations_model)
        self.operations_model.configureView()
        self.OperationsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.connect_signals_and_slots()

        self.NewOperationMenu = QMenu()
        for i in range(self.OperationsTabs.count()):
            if hasattr(self.OperationsTabs.widget(i), "isCustom"):
                self.OperationsTabs.widget(i).dbUpdated.connect(
                    self.ledger.rebuild)
                self.OperationsTabs.widget(i).dbUpdated.connect(
                    self.operations_model.refresh)
                self.NewOperationMenu.addAction(
                    self.OperationsTabs.widget(i).name,
                    partial(self.createOperation, i))
        self.NewOperationBtn.setMenu(self.NewOperationMenu)

        # Setup balance and holdings parameters
        current_time = QDateTime.currentDateTime()
        current_time.setTimeSpec(
            Qt.UTC)  # We use UTC everywhere so need to force TZ info
        self.BalanceDate.setDateTime(current_time)
        self.BalancesCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))
        self.HoldingsDate.setDateTime(current_time)
        self.HoldingsCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))

        self.OperationsTabs.setCurrentIndex(TransactionType.NA)
        self.OperationsTableView.selectRow(0)
        self.OnOperationsRangeChange(0)
Exemplo n.º 24
0
Arquivo: main.py Projeto: KDAB/KDChart
    def __init__(self):
        super(MyWidget, self).__init__(None)

        self.view = View()
        self.grid = DateTimeGrid()
        self.slider = QSlider()
        self.model = QStandardItemModel()
        self.cmodel = ConstraintModel()

        for h in range(0, 19):
            topitem = MyStandardItem("Top Item " + str(h))
            for i in range(0, 19):
                item = MyStandardItem("Multi Item " + str(i))
                for j in range(0, 29, 3):
                    item.appendRow([
                        MyStandardItem("Item " + str(j)),
                        MyStandardItem(KDGantt.TypeTask),
                        MyStandardItem(QDateTime.currentDateTime().addDays(j),
                                       KDGantt.StartTimeRole),
                        MyStandardItem(
                            QDateTime.currentDateTime().addDays(j + 1 + i / 7),
                            KDGantt.EndTimeRole),
                        MyStandardItem(50)
                    ])

                item.appendRow([
                    MyStandardItem("Event"),
                    MyStandardItem(KDGantt.TypeEvent),
                    MyStandardItem(QDateTime.currentDateTime(),
                                   KDGantt.StartTimeRole),
                    MyStandardItem(QDateTime(), KDGantt.EndTimeRole),
                    MyStandardItem("")
                ])

                topitem.appendRow([
                    item,
                    MyStandardItem(KDGantt.TypeMulti),
                    MyStandardItem(""),
                    MyStandardItem(""),
                    MyStandardItem("")
                ])

            self.model.appendRow([
                topitem,
                MyStandardItem(KDGantt.TypeMulti),
                MyStandardItem(""),
                MyStandardItem(""),
                MyStandardItem("")
            ])

        self.model.appendRow([MyStandardItem("No data")])

        ##cmodel.addConstraint( KDGantt::Constraint( proxyModel.index( 0, 3 ), proxyModel.index( 10, 3 ) ) );
        ##cmodel.addConstraint( KDGantt::Constraint( proxyModel.index( 10, 3 ), proxyModel.index( 5, 3 ) ) );
        pidx = self.model.index(0, 0)
        pidx = self.model.index(0, 0, pidx)
        self.cmodel.addConstraint(
            Constraint(self.model.index(0, 0, pidx),
                       self.model.index(1, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(1, 0, pidx),
                       self.model.index(0, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(1, 0, pidx),
                       self.model.index(10, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(3, 0, pidx),
                       self.model.index(5, 0, pidx)))
        self.cmodel.addConstraint(
            Constraint(self.model.index(7, 0, pidx),
                       self.model.index(4, 0, pidx)))

        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setRange(1, 10000)
        self.slider.setValue(100)
        l = QVBoxLayout(self)
        l.addWidget(self.view)
        l.addWidget(self.slider)
        self.grid.setStartDateTime(QDateTime.currentDateTime().addDays(-3))
        self.grid.setDayWidth(100)
        ##grid.setNoInformationBrush( Qt::NoBrush );
        self.view.setGrid(self.grid)
        self.view.setModel(self.model)
        ##view.setConstraintModel( &cmodel );
        self.slider.valueChanged.connect(self.slotZoom)

        pb1 = QPushButton("Print Preview...", self)
        pb2 = QPushButton("Print...", self)

        l.addWidget(pb1)
        l.addWidget(pb2)

        pb1.clicked.connect(self.slotPrintPreview)
        pb2.clicked.connect(self.slotPrint)

        gv = self.view.graphicsView()
        gv.setHeaderContextMenuPolicy(Qt.CustomContextMenu)
        gv.headerContextMenuRequested.connect(self.slotHeaderMenu)
Exemplo n.º 25
0
Arquivo: main.py Projeto: KDAB/KDChart
 def currentRangeBegin(self, datetime):
     dt = QDateTime(datetime)
     dt.setTime(
         QTime(dt.time().hour(), (dt.time().minute() / 10) * 10, 0, 0))
     return dt
Exemplo n.º 26
0
    app = QApplication(sys.argv)

    view = GraphicsView()
    rowController = MyRowController()
    view.setReadOnly(True)
    view.setRowController(rowController)
    view.show()

    model = MyStandardItemModel()
    for i in range(0, 10):
        items = []
        for j in range(0, 10):
            item = QStandardItem()
            item.setText("Item " + str(i))
            item.setData(2, KDGantt.ItemTypeRole)
            item.setData(
                QDateTime.currentDateTime().addDays(2 * j).addMSecs(
                    100000 * i), KDGantt.StartTimeRole)
            item.setData(
                QDateTime.currentDateTime().addDays(2 * j + 1).addMSecs(
                    100000 * i), KDGantt.EndTimeRole)
            item.setData(random_alignment(), Qt.TextAlignmentRole)
            item.setData(random_position(), KDGantt.TextPositionRole)
            item.setFlags(item.flags() & ~Qt.ItemIsSelectable)
            items.append(item)
        model.appendRow(items)

    rowController.setModel(model)
    view.setModel(model)
    sys.exit(app.exec_())
Exemplo n.º 27
0
    def parseJSON(self):
        # Slip data might be in a root element or in ticket/document/receipt
        if 'ticket' in self.slip_json:
            sub = self.slip_json['ticket']
            if 'document' in sub:
                sub = sub['document']
                if 'receipt' in sub:
                    slip = sub['receipt']
                else:
                    logging.error(self.tr("Can't find 'receipt' tag in json 'document'"))
                    return
            else:
                logging.error(self.tr("Can't find 'document' tag in json 'ticket'"))
                return
        else:
            slip = self.slip_json

        # Get operation type
        operation = 0
        if 'operationType' in slip:
            operation = int(slip['operationType'])
        else:
            logging.error(self.tr("Can't find 'operationType' tag in json 'ticket'"))
            return
        # Get shop name
        shop_name = ''
        if 'user' in slip:
            shop_name = self.SlipShopName.setText(slip['user'])
        if (not shop_name) and ('userInn' in slip):
            shop_name = self.slipsAPI.get_shop_name_by_inn(slip['userInn'])
        self.SlipShopName.setText(shop_name)

        peer_id = self.match_shop_name(self.SlipShopName.text())
        if peer_id is not None:
            self.PeerEdit.selected_id = peer_id

        try:
            self.slip_lines = pd.DataFrame(slip['items'])
        except:
            return

        # Get date from timestamp
        if 'dateTime' in slip:
            slip_datetime = QDateTime.fromSecsSinceEpoch(int(slip['dateTime']))
            slip_datetime.setTimeSpec(Qt.UTC)
            self.SlipDateTime.setDateTime(slip_datetime)

        # Convert price to roubles
        self.slip_lines['price'] = self.slip_lines['price'] / 100
        if operation == self.OPERATION_PURCHASE:
            self.slip_lines['sum'] = -self.slip_lines['sum'] / 100
        elif operation == self.OPERATION_RETURN:
            self.slip_lines['sum'] = self.slip_lines['sum'] / 100
        else:
            logging.error(self.tr("Unknown operation type ") + f"{operation}")
            return
        # Use quantity if it differs from 1 unit value
        self.slip_lines.loc[self.slip_lines['quantity'] != 1, 'name'] = \
            self.slip_lines.agg('{0[name]} ({0[quantity]:g} x {0[price]:.2f})'.format, axis=1)
        # Assign empty category
        self.slip_lines['category'] = 0
        self.slip_lines['confidence'] = 1
        # Assign empty tags
        self.slip_lines['tag'] = None
        self.slip_lines = self.slip_lines[['name', 'category', 'confidence', 'tag', 'sum']]

        self.model = PandasLinesModel(self.slip_lines)
        self.LinesTableView.setModel(self.model)

        self.delegate = SlipLinesDelegate(self.LinesTableView)
        for column in range(self.model.columnCount()):
            if column == 0:
                self.LinesTableView.horizontalHeader().setSectionResizeMode(column, QHeaderView.Stretch)
            elif column == 1:
                self.LinesTableView.setColumnWidth(column, 200)
            elif column == 2:
                self.LinesTableView.setColumnHidden(column, True)
            else:
                self.LinesTableView.setColumnWidth(column, 100)
            self.LinesTableView.setItemDelegateForColumn(column, self.delegate)
        font = self.LinesTableView.horizontalHeader().font()
        font.setBold(True)
        self.LinesTableView.horizontalHeader().setFont(font)
        self.LinesTableView.show()
        self.qr_data_loaded.emit()
Exemplo n.º 28
0
 def keyPressEvent(self, event: QKeyEvent) -> None:
     if event.key() == Qt.Key_Minus:
         self.setDateTime(
             QDateTime(QDate(1970, 1, 1), QTime(0, 0, 0),
                       Qt.UTC))  # = 0 timestamp
     super().keyPressEvent(event)