Exemplo 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.
            re = QRegularExpression("^[{}].*".format(group))
            assert re.isValid()
            re.setPatternOptions(QRegularExpression.CaseInsensitiveOption)
            proxyModel.setFilterRegularExpression(re)
            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)
Exemplo n.º 2
0
class Table(QWidget):

    def __init__(self, arg=None):
        super(Table, self).__init__(arg)
        # 设置窗体的标题和初始大小
        self.setWindowTitle("QTableView 表格视图控件的例子")
        self.resize(600, 300)

        # 准备数据模型,设置数据层次结构为6行5列
        self.model = QStandardItemModel(6, 5)
        # 设置数据栏名称
        self.model.setHorizontalHeaderLabels(['标题1', '标题2', '标题3', '标题4',  '标题5'])

        for row in range(6):
            for column in range(5):
                item = QStandardItem("行 %s, 列 %s" % (row, column ))
                self.model.setItem(row, column, item)

        # 实例化表格视图,设置模型为自定义的模型
        self.tableView = QTableView()
        self.tableView.setModel(self.model)

        ############ 下面代码让表格 100% 的填满窗口
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 局部布局
        vboxLayout = QVBoxLayout()
        vboxLayout.addWidget(self.tableView)
        # 全局布局
        wl = QVBoxLayout(self)
        wl.addLayout(vboxLayout)
Exemplo n.º 3
0
class TableWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.model = CustomTableModel()

        self.table_view = QTableView()
        self.table_view.setModel(self.model)
        self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table_view.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

        self.chart = QtCharts.QChart()
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)

        self.series = QtCharts.QLineSeries()
        self.series.setName("Line 1")
        self.mapper = QtCharts.QVXYModelMapper(self)
        self.mapper.setXColumn(0)
        self.mapper.setYColumn(1)
        self.mapper.setSeries(self.series)
        self.mapper.setModel(self.model)
        self.chart.addSeries(self.series)

        # for storing color hex from the series
        seriesColorHex = "#000000"

        # get the color of the series and use it for showing the mapped area
        seriesColorHex = "{}".format(self.series.pen().color().name())
        self.model.add_mapping(seriesColorHex, QRect(0, 0, 2, self.model.rowCount()))

        # series 2
        self.series = QtCharts.QLineSeries()
        self.series.setName("Line 2")

        self.mapper = QtCharts.QVXYModelMapper(self)
        self.mapper.setXColumn(2)
        self.mapper.setYColumn(3)
        self.mapper.setSeries(self.series)
        self.mapper.setModel(self.model)
        self.chart.addSeries(self.series)

        # get the color of the series and use it for showing the mapped area
        seriesColorHex = "{}".format(self.series.pen().color().name())
        self.model.add_mapping(seriesColorHex, QRect(2, 0, 2, self.model.rowCount()))

        self.chart.createDefaultAxes()
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setMinimumSize(640, 480)

        # create main layout
        self.main_layout = QGridLayout()
        self.main_layout.addWidget(self.table_view, 1, 0)
        self.main_layout.addWidget(self.chart_view, 1, 1)
        self.main_layout.setColumnStretch(1, 1)
        self.main_layout.setColumnStretch(0, 0)
        self.setLayout(self.main_layout)
Exemplo n.º 4
0
class DebugBreakpointsWidget(QWidget, DockContextHandler):
    def __init__(self, parent, name, data):
        if not type(data) == BinaryView:
            raise Exception('expected widget data to be a BinaryView')

        self.bv = data

        QWidget.__init__(self, parent)
        DockContextHandler.__init__(self, self, name)
        self.actionHandler = UIActionHandler()
        self.actionHandler.setupActionHandler(self)

        self.table = QTableView(self)
        self.model = DebugBreakpointsListModel(self.table, data)
        self.table.setModel(self.model)

        self.item_delegate = DebugBreakpointsItemDelegate(self)
        self.table.setItemDelegate(self.item_delegate)

        # self.table.setSortingEnabled(True)
        self.table.setSelectionBehavior(
            QAbstractItemView.SelectionBehavior.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.table.verticalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.table.verticalHeader().setVisible(False)

        self.table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        self.table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)

        self.table.resizeColumnsToContents()
        self.table.resizeRowsToContents()
        self.table.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.table)
        self.setLayout(layout)

    def notifyOffsetChanged(self, offset):
        pass

    def notifyBreakpointsChanged(self, new_rows):
        self.model.update_rows(new_rows)

    def contextMenuEvent(self, event):
        self.m_contextMenuManager.show(self.m_menu, self.actionHandler)

    def shouldBeVisible(self, view_frame):
        if view_frame is None:
            return False
        else:
            return True
Exemplo n.º 5
0
class ChannelPropertiesDialog(QDialog):
    def __init__(self, parent, info, title="Channel Properties"):
        super().__init__(parent)
        self.setWindowTitle(title)

        self.model = QStandardItemModel(info["nchan"], 4)
        self.model.setHorizontalHeaderLabels(["#", "Label", "Type", "Bad"])
        for index, ch in enumerate(info["chs"]):
            item = QStandardItem()
            item.setData(index, Qt.DisplayRole)
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)
            self.model.setItem(index, 0, item)
            self.model.setItem(index, 1, QStandardItem(ch["ch_name"]))
            kind = channel_type(info, index).upper()
            self.model.setItem(index, 2, QStandardItem(str(kind)))
            bad = QStandardItem()
            bad.setData(ch["ch_name"] in info["bads"], Qt.UserRole)
            bad.setCheckable(True)
            bad.setEditable(False)
            checked = ch["ch_name"] in info["bads"]
            bad.setCheckState(Qt.Checked if checked else Qt.Unchecked)
            self.model.setItem(index, 3, bad)

        self.model.itemChanged.connect(bad_changed)
        self.proxymodel = MySortFilterProxyModel()
        self.proxymodel.setDynamicSortFilter(False)
        self.proxymodel.setSourceModel(self.model)

        self.view = QTableView()
        self.view.setModel(self.proxymodel)
        self.view.setItemDelegateForColumn(2, ComboBoxDelegate(self.view))
        self.view.setEditTriggers(QAbstractItemView.AllEditTriggers)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setShowGrid(False)
        self.view.setSelectionMode(QAbstractItemView.NoSelection)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.AscendingOrder)

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.view)
        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        vbox.addWidget(self.buttonbox)
        self.buttonbox.accepted.connect(self.accept)
        self.buttonbox.rejected.connect(self.reject)

        self.resize(475, 650)
        self.view.setColumnWidth(0, 70)
        self.view.setColumnWidth(1, 155)
        self.view.setColumnWidth(2, 90)
 def show_play_table(self, plays):
     """Shows a table with all the plays to be imported, allowing user to select some to skip"""
     tree_model = PlayTableModel(plays)
     table_widget = QTableView()
     table_widget.setModel(tree_model)
     table_widget.verticalHeader().setVisible(False)
     table_view_header = table_widget.horizontalHeader()
     table_view_header.setStretchLastSection(True)
     for column in range(tree_model.columnCount()):
         column_size = tree_model.data(tree_model.index(0, column),
                                       PlayTableModel.SIZE_ROLE)
         table_view_header.resizeSection(column, column_size)
     table_widget_dialog = QDialog(self)
     table_widget_dialog.setModal(True)
     grid_layout = QGridLayout(table_widget_dialog)
     grid_layout.addWidget(table_widget, 1, 1)
     table_widget_dialog.resize(800, 600)
     table_widget_dialog.exec_()
     skipped_plays = tree_model.get_skipped_plays()
     return [play for play in plays if play.id not in skipped_plays]
class IngestWindow(QDialog):
    """Subwindow dedicated to data ingest functions.

    Instance attributes:
        - config: Config object holding configuration information
        including API keys.
    """
    config: Config

    # Private Instance Attributes:
    # - _main_layout: Main grid layout
    # - _button_box: Button box holding main control buttons.
    # - _options_group_box: Group box holding most UI widgets
    # - _view: QTableView holding the pandas table viewer.
    # - _pool: QThreadPool for handeling multithreaded functions.
    # - _txt_var: Dictionary holding line edit widgets.
    # - _lists: Dictionary holding the dataset list widget and search type combo widget.
    _main_layout: QGridLayout
    _button_box: QDialogButtonBox
    _options_group_box: QGroupBox
    _view: QTableView
    _pool: QThreadPool
    _delete_btn: QDialogButtonBox
    _txt_var: dict[str, QLineEdit] = {}
    _lists: dict[str, Union[QListWidget, QComboBox]] = {}

    def __init__(self, config: Config) -> None:
        super().__init__()

        self._pool = QThreadPool.globalInstance()

        self._view = QTableView()
        self._view.horizontalHeader().setCascadingSectionResizes(True)
        self._view.horizontalHeader().setStretchLastSection(True)
        self._view.setAlternatingRowColors(True)
        self._view.setSelectionBehavior(QTableView.SelectRows)

        self.config = config

        self._init_options_group_box()
        self._init_button_box()

        main_layout = QGridLayout()
        main_layout.addWidget(self._options_group_box, 0, 0)
        main_layout.addWidget(self._button_box, 1, 0)
        main_layout.addWidget(self._view, 2, 0)
        main_layout.setSizeConstraint(QLayout.SetMinimumSize)

        self._main_layout = main_layout
        self.setLayout(self._main_layout)
        self._type_changed()

        self.setWindowTitle('Train Model')

    def show(self) -> None:
        """Override of QWidget's show() function.

        Refreshes window and then shows the window.
        """
        super().show()
        self._refresh_lists()
        self._refresh_pandas()

    def _init_button_box(self) -> None:
        """Creates the lower control buttons at the bottom of the window."""
        self._button_box = QDialogButtonBox()

        ingest_btn = self._button_box.addButton('Get Data',
                                                QDialogButtonBox.ActionRole)
        self._delete_btn = self._button_box.addButton(
            'Delete Dataset', QDialogButtonBox.ActionRole)
        refresh_btn = self._button_box.addButton('Refresh &Options',
                                                 QDialogButtonBox.ActionRole)

        ingest_btn.clicked.connect(self._ingest)
        self._delete_btn.clicked.connect(self._delete)
        refresh_btn.clicked.connect(self._refresh_lists)

    def _init_options_group_box(self) -> None:
        """Creates the group of training options."""
        self._options_group_box = QGroupBox("Options")

        options_layout = QGridLayout()
        left_options = QGridLayout()
        right_options = QGridLayout()

        self._lists['data'] = QListWidget()
        self._lists['data'].setSelectionMode(
            QtWidgets.QAbstractItemView.SingleSelection)
        self._lists['data'].currentTextChanged.connect(self._refresh_pandas)

        self._lists['type'] = QComboBox()
        for dt in IngestTypes:
            self._lists['type'].addItem(dt.value)

        self._refresh_lists()

        self._lists['type'].currentTextChanged.connect(self._type_changed)

        validator = QRegularExpressionValidator(r'^[\w\-. ]+$')
        cat_validator = QRegularExpressionValidator(r'^[0-9]\d*$')

        dataset_label = QLabel("Avaliable Datasets:")
        search_type_label = QLabel("Symbol/Search Type:")
        search_label = QLabel("Symbol/Search Term:")
        name_label = QLabel("Dataset Name:")
        cat_label = QLabel("Trends Category Code:")

        left_options.addWidget(dataset_label, 0, 0)
        left_options.addWidget(self._lists['data'], 1, 0)

        right_options.addWidget(search_type_label, 0, 0)
        right_options.addWidget(self._lists['type'], 1, 0)

        self._txt_var['ds_name'] = QLineEdit()
        self._txt_var['data_search'] = QLineEdit()
        self._txt_var['search_cat'] = QLineEdit()
        self._txt_var['ds_name'].setValidator(validator)
        self._txt_var['data_search'].setValidator(validator)
        self._txt_var['search_cat'].setValidator(cat_validator)

        self._txt_var['search_cat'].setPlaceholderText('0')

        right_options.addWidget(search_label, 2, 0)
        right_options.addWidget(self._txt_var['data_search'], 3, 0)

        right_options.addWidget(name_label, 4, 0)
        right_options.addWidget(self._txt_var['ds_name'], 5, 0)

        right_options.addWidget(cat_label, 6, 0)
        right_options.addWidget(self._txt_var['search_cat'], 7, 0)

        options_layout.addLayout(left_options, 0, 0)
        options_layout.addLayout(right_options, 0, 1)

        options_layout.setColumnStretch(0, 1)

        self._options_group_box.setLayout(options_layout)

    def _refresh_lists(self) -> None:
        """Refreshes avaliable datasets for training."""
        self._lists['data'].clear()

        data_list = data_ingest.get_avaliable_data(search_type='data')

        self._lists['data'].addItems(data_list)

    def _refresh_pandas(self) -> None:
        """Refreshes the pandas table viewer."""
        df = self._lists['data'].currentItem()
        if df is not None:
            df = df.text()
            if df in data_ingest.get_avaliable_data(search_type='data'):
                df = data_ingest.load_data(df)
                model = PandasModel(df)
                self._view.setModel(model)
                self._delete_btn.setEnabled(True)
                return

        self._delete_btn.setEnabled(False)

    def _type_changed(self) -> None:
        """Updates widget based on type combo box change."""
        if self._lists['type'].currentText() == 'Google Trends':
            self._txt_var['ds_name'].setEnabled(False)
            self._txt_var['search_cat'].setEnabled(True)
        else:
            self._txt_var['ds_name'].setEnabled(True)
            self._txt_var['search_cat'].setEnabled(False)

    def _ingest(self) -> None:
        """Ingests the user requested data and saves it accordingly."""
        self.setEnabled(False)
        search_type = self._lists['type'].currentText()
        search_type = IngestTypes.from_str(search_type)

        search_term = self._txt_var['data_search'].text().strip()
        self._txt_var['data_search'].setText(search_term)

        if search_type in {
                IngestTypes.CryptoCurrenciesDaily,
                IngestTypes.TimeSeriesDailyAdjusted
        }:
            try:
                if search_type == IngestTypes.CryptoCurrenciesDaily:
                    data = data_ingest.async_get([
                        data_ingest.get_cc_daily(search_term,
                                                 self.config,
                                                 cache=False)
                    ])[0]
                elif search_type == IngestTypes.TimeSeriesDailyAdjusted:
                    data = data_ingest.async_get([
                        data_ingest.get_ts_daily_adjusted(search_term,
                                                          self.config,
                                                          cache=False)
                    ])[0]
                else:
                    data = None  # Satisfy PyTa even though raise occurs
                    raise NotImplementedError
            except ce.RateLimited:
                self._error_event(
                    'You are being rate limited. Check Alpha Vantage API key or wait.'
                )
                return
            except ce.UnknownAVType:
                self._error_event(
                    f'{search_term} is an invalid symbol for {search_type}')
                return
        elif search_type == IngestTypes.GoogleTrends:
            trends_thread = TrendsThread(search_term,
                                         self._txt_var['search_cat'].text())

            self._pool.start(trends_thread)

            trends_thread.signals.error.connect(self._error_event)

            trends_thread.signals.dataframe_result.connect(self._ingest_save)
            return
        else:
            self._error_event('Invalid search type.')
            return

        self._ingest_save(data)

    def _ingest_save(self, data: pd.DataFrame) -> None:
        """Generates a name and saves the given dataframe.
        Returns None when complete or on error."""
        search_type = self._lists['type'].currentText()
        search_term = self._txt_var['data_search'].text()

        search_type = IngestTypes.from_str(search_type)
        if search_type == IngestTypes.GoogleTrends:
            cat = self._txt_var['search_cat'].text()

            if cat == '':
                cat = '0'
            name = f'{search_term} {cat};{data_ingest.IngestTypes.GoogleTrends.name}'
        else:
            name = self._txt_var['ds_name'].text()
            if name == '':
                name = data_ingest.name_generator(search_term, search_type)
            else:
                name = data_ingest.name_generator(search_term, search_type,
                                                  name)

        current_datasets = data_ingest.get_avaliable_data(search_type='data')

        if name in current_datasets:
            response = self._error_event(f'{name} will be overwritten.',
                                         choice=True)
            if response == QMessageBox.Abort:
                self.setEnabled(True)
                return

        data_ingest.save_data(name, data)

        self._refresh_lists()
        self.setEnabled(True)

    def _delete(self) -> None:
        """Deletes the currently selected dataset."""
        self.setEnabled(False)
        name = self._lists['data'].selectedItems()

        if len(name) != 0:
            name = name[0].text()

            warning = f'Are you sure you want to delete {name}?'

            response = QMessageBox.warning(self, self.tr("Delete Dataset"),
                                           warning, QMessageBox.Yes,
                                           QMessageBox.No)
            if response == QMessageBox.Yes:
                data_ingest.delete_data(name, file_type='data')
                self._refresh_lists()

        self.setEnabled(True)

    def _error_event(
        self,
        error: str,
        choice: bool = False,
        btn: QMessageBox = QMessageBox.Abort
    ) -> Union[QMessageBox.Ignore, QMessageBox.Abort, None]:
        """Displays an error message with the given error."""
        if choice:
            response = QMessageBox.critical(self, self.tr("Error"), error, btn,
                                            QMessageBox.Ignore)
            return response
        else:
            QMessageBox.critical(self, self.tr("Error"), error, QMessageBox.Ok)
            self.setEnabled(True)
            return None
Exemplo n.º 8
0
class Table(QWidget):

    def __init__(self, arg=None):
        super(Table, self).__init__(arg)
        # 设置窗体的标题和初始大小
        self.setWindowTitle("QTableView表格视图控件的例子")
        self.resize(500, 300)

        # 准备数据模型,设置数据层次结构为5行4列
        self.model = QStandardItemModel(5, 4)
        # 设置数据栏名称
        self.model.setHorizontalHeaderLabels(['标题1', '标题2', '标题3', '标题4'])

        for row in range(5):
            for column in range(4):
                item = QStandardItem("row %s, column %s" % (row, column))
                self.model.setItem(row, column, item)

        # 实例化表格视图,设置模型为自定义的模型
        self.tableView = QTableView()
        self.tableView.setModel(self.model)

        # 下面代码让表格 100% 的填满窗口
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 下面代码让表格禁止编辑
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # 下面代码让表格设置选中背景色
        self.tableView.setStyleSheet("selection-background-color:lightblue;")

        # 下面代码要限定只能选择整行
        # self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置只能选中整行
        # self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行

        # 下面代码可以选中表格的多行
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置只能选中整行
        self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection)  # 设置只能选中多行

        # 下面代码可以打印表格的1行2列数据
        data = self.tableView.model().index(1, 2).data()
        print(data)

        # 下面代码去掉左边表格的行号
        # headerView  = self.tableView.verticalHeader()
        # headerView.setHidden(True)

        # 局部布局
        vboxLayout = QVBoxLayout()
        vboxLayout.addWidget(self.tableView)
        self.add_btn = QPushButton("添加记录")
        # 连接信号槽,点击按钮 add_btn 绑定槽事件
        self.add_btn.clicked.connect(self.add_records_btn_click)

        self.del_btn = QPushButton("删除多行记录")
        # 连接信号槽,点击按钮 del_btn 绑定槽事件
        self.del_btn.clicked.connect(self.del_records_btn_click)
        # 局部布局
        hboxLayout = QHBoxLayout()
        hboxLayout.addWidget(self.add_btn)
        hboxLayout.addWidget(self.del_btn)

        # 全局布局
        wl = QVBoxLayout(self)
        wl.addLayout(vboxLayout)
        wl.addLayout(hboxLayout)

    # 点击删除按钮响应方法, 删除选中的单行数据
    def del_record_btn_click(self):
        # 第一种方法: 删除单行数据
        indices = self.tableView.selectionModel().selectedRows()
        for index in sorted(indices):
            self.model.removeRow(index.row())

        # 第二种方法: 删除单行数据
        # index = self.tableView.currentIndex()  # 取得当前选中行的index
        # if -1 == index.row():
        #     return
        # self.model.removeRow(index.row())  # 通过index的row()操作得到行数进行删除

    # 点击删除按钮响应方法, 删除选中的多行数据
    def del_records_btn_click(self):
        # 第一种方法:删除多行数据
        index_list = []
        for model_index in self.tableView.selectionModel().selectedRows():
            index = QtCore.QPersistentModelIndex(model_index)
            index_list.append(index)

        if index_list:
            for index in index_list:
                self.model.removeRow(index.row())
        else:
            MessageBox = QMessageBox()
            MessageBox.information(self.tableView, "标题", "没有选中表格中要删除的行")

        # 第二种方法:删除多行数据
        # indexs = self.tableView.selectionModel().selectedRows()
        # temp_list = []  # 创建一个空队列用于存放需要删除的行号
        # for index in indexs:
        #     temp_list.append(index.row())  # 队列中保存需要删除的行号
        # temp_list.sort(key=int, reverse=True)  # 用sort方法将队列进行降序排列
        # print(temp_list)
        #
        # if temp_list:
        #     for i in temp_list:  # 按照队列删除对应的行
        #         self.model.removeRow(i)
        # else:
        #     MessageBox = QMessageBox()
        #     MessageBox.information(self.tableView, "标题", "没有选中表格中要删除的行")

    # 点击添加按钮相应方法,添加数据
    def add_records_btn_click(self):
        self.model.appendRow([
            QStandardItem("row %s, column %s" % (5, 0)),
            QStandardItem("row %s, column %s" % (6, 1)),
            QStandardItem("row %s, column %s" % (7, 2)),
            QStandardItem("row %s, column %s" % (8, 3)),
        ])
Exemplo n.º 9
0
class MainWindow(QWidget):
    '''
    Объявление UI для программы
    '''
    def __init__(self, parent):
        super(MainWindow, self).__init__()
        self._width = 360
        self._height = 320
        self.setMinimumSize(self._width, self._height)
        self.setMaximumSize(self._width, self._height)
        #self.resize(self._width, self._height)
        self.setWindowTitle('0-бед or 0-bet')
        self.VBox = QVBoxLayout(self)
        self.VBox.setContentsMargins(5, 5, 5, 5)
        self.restText = QLabel(self)
        self.restText.setText("Список заведений: ")
        self.restTable = QTableView(self)
        self.sep1 = QFrame(self)
        self.sep1.setFrameShape(QFrame.HLine)
        self.sep1.setFrameShadow(QFrame.Sunken)
        self.restUnitName = QLineEdit(self)
        self.restAddButt = QPushButton(self)
        self.restAddButt.setText('Добавить заведение')
        self.restRmvButt = QPushButton(self)
        self.restRmvButt.setText('Удалить заведение')
        self.sep2 = QFrame(self)
        self.sep2.setFrameShape(QFrame.HLine)
        self.sep2.setFrameShadow(QFrame.Sunken)
        self.restLotteryButt = QPushButton(self)
        self.restLotteryButt.setText('Лотерея')

        self.VBox.addWidget(self.restText)
        self.VBox.addWidget(self.restTable)
        self.VBox.addWidget(self.sep1)
        self.VBox.addWidget(self.restUnitName)
        self.VBox.addWidget(self.restAddButt)
        self.VBox.addWidget(self.restRmvButt)
        self.VBox.addWidget(self.sep2)
        self.VBox.addWidget(self.restLotteryButt)
        self.setLayout(self.VBox)

        self.restAddButt.clicked.connect(self.addRestItem)
        self.restLotteryButt.clicked.connect(self.startLottery)
        self.restRmvButt.clicked.connect(self.removeRestItem)
        self.restTable.clicked.connect(self.selectRest)

        self.name_list = []
        self.reqCount_list = []
        self.sg = Sig()
        parent.sg.updateTable.connect(self.updTbl)

    def addRestItem(self):
        name = self.restUnitName.text()
        if name in self.name_list:
            self.reqCount_list[self.name_list.index(
                name)] = self.reqCount_list[self.name_list.index(name)] + 1
        else:
            self.name_list.append(name)
            self.reqCount_list.append(1)
        table_model = RestaurantTableModeL(self.name_list, self.reqCount_list)
        self.restTable.setModel(table_model)
        self.restTable.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.restTable.horizontalHeader().setStretchLastSection(True)

    def startLottery(self):
        self.sg.lists.emit(self.name_list, self.reqCount_list)

    def selectRest(self):
        self.idx = self.restTable.currentIndex()
        self.restTable.selectRow(self.idx.row())

    def removeRestItem(self):
        self.idx = self.restTable.currentIndex()
        if self.reqCount_list[self.idx.row()] > 1:
            self.reqCount_list[self.idx.row()] -= 1
        else:
            self.name_list.pop(self.idx.row())
            self.reqCount_list.pop(self.idx.row())
        table_model = RestaurantTableModeL(self.name_list, self.reqCount_list)
        self.restTable.setModel(table_model)
        self.restTable.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.restTable.horizontalHeader().setStretchLastSection(True)

    @Slot(list)
    def updTbl(self, cnt):
        table_model = RestaurantTableModeL(self.name_list, self.reqCount_list,
                                           cnt)
        self.restTable.setModel(table_model)
        self.restTable.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.restTable.horizontalHeader().setStretchLastSection(True)
Exemplo n.º 10
0
class Ui_testGlWindow(object):
    def setupUi(self, testGlWindow):
        if not testGlWindow.objectName():
            testGlWindow.setObjectName(u"testGlWindow")
        testGlWindow.resize(952, 847)
        testGlWindow.setAcceptDrops(True)
        icon = QIcon()
        icon.addFile(u":/images/candle_256.png", QSize(), QIcon.Normal,
                     QIcon.Off)
        testGlWindow.setWindowIcon(icon)
        testGlWindow.setStyleSheet(u"")
        self.centralWidget = QWidget(testGlWindow)
        self.centralWidget.setObjectName(u"centralWidget")
        self.horizontalLayout_5 = QHBoxLayout(self.centralWidget)
        self.horizontalLayout_5.setSpacing(9)
        self.horizontalLayout_5.setContentsMargins(11, 11, 11, 11)
        self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
        self.horizontalLayout_5.setContentsMargins(9, 9, 5, 9)
        self.grpProgram = QGroupBox(self.centralWidget)
        self.grpProgram.setObjectName(u"grpProgram")
        self.grpProgram.setFlat(False)
        self.verticalLayout_17 = QVBoxLayout(self.grpProgram)
        self.verticalLayout_17.setSpacing(7)
        self.verticalLayout_17.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout_17.setObjectName(u"verticalLayout_17")
        self.verticalLayout_17.setContentsMargins(8, 8, 8, 8)
        self.splitter = QSplitter(self.grpProgram)
        self.splitter.setObjectName(u"splitter")
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(12)
        self.frame = QWidget(self.splitter)
        self.frame.setObjectName(u"frame")
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame.sizePolicy().hasHeightForWidth())
        self.frame.setSizePolicy(sizePolicy)
        self.frame.setMinimumSize(QSize(0, 600))
        self.frame.setStyleSheet(u"border: 1px solid gray;")
        self.verticalLayout_8 = QVBoxLayout(self.frame)
        self.verticalLayout_8.setSpacing(6)
        self.verticalLayout_8.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout_8.setObjectName(u"verticalLayout_8")
        self.verticalLayout_8.setContentsMargins(1, 1, 1, 1)
        self.splitter.addWidget(self.frame)
        self.layoutWidget = QWidget(self.splitter)
        self.layoutWidget.setObjectName(u"layoutWidget")
        self.verticalLayout_7 = QVBoxLayout(self.layoutWidget)
        self.verticalLayout_7.setSpacing(9)
        self.verticalLayout_7.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout_7.setObjectName(u"verticalLayout_7")
        self.verticalLayout_7.setContentsMargins(0, 0, 0, 0)
        self.tblProgram = QTableView(self.layoutWidget)
        self.tblProgram.setObjectName(u"tblProgram")
        font = QFont()
        font.setPointSize(9)
        self.tblProgram.setFont(font)
        self.tblProgram.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tblProgram.setEditTriggers(QAbstractItemView.AnyKeyPressed
                                        | QAbstractItemView.DoubleClicked
                                        | QAbstractItemView.EditKeyPressed
                                        | QAbstractItemView.SelectedClicked)
        self.tblProgram.setSelectionMode(QAbstractItemView.ContiguousSelection)
        self.tblProgram.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tblProgram.setGridStyle(Qt.DashLine)
        self.tblProgram.horizontalHeader().setMinimumSectionSize(50)
        self.tblProgram.horizontalHeader().setHighlightSections(False)
        self.tblProgram.verticalHeader().setVisible(False)

        self.verticalLayout_7.addWidget(self.tblProgram)

        self.splitter.addWidget(self.layoutWidget)

        self.verticalLayout_17.addWidget(self.splitter)

        self.verticalLayout_17.setStretch(0, 1)

        self.horizontalLayout_5.addWidget(self.grpProgram)

        self.horizontalLayout_5.setStretch(0, 100)
        testGlWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(testGlWindow)
        self.menuBar.setObjectName(u"menuBar")
        self.menuBar.setGeometry(QRect(0, 0, 952, 21))
        testGlWindow.setMenuBar(self.menuBar)

        self.retranslateUi(testGlWindow)

        QMetaObject.connectSlotsByName(testGlWindow)

    # setupUi

    def retranslateUi(self, testGlWindow):
        testGlWindow.setWindowTitle(
            QCoreApplication.translate("testGlWindow", u"Candle", None))
        self.grpProgram.setTitle(
            QCoreApplication.translate("testGlWindow", u"G-code program",
                                       None))
Exemplo n.º 11
0
class XDFStreamsDialog(QDialog):
    def __init__(self, parent, rows, selected=None, disabled=None):
        super().__init__(parent)
        self.setWindowTitle("Select XDF Stream")

        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(
            ["ID", "Name", "Type", "Channels", "Format", "Sampling Rate"])

        for index, stream in enumerate(rows):
            items = []
            for item in stream:
                tmp = QStandardItem()
                tmp.setData(item, Qt.DisplayRole)
                items.append(tmp)
            for item in items:
                item.setEditable(False)
                if disabled is not None and index in disabled:
                    item.setFlags(Qt.NoItemFlags)
            self.model.appendRow(items)

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setShowGrid(False)
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        if selected is not None:
            self.view.selectRow(selected)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.AscendingOrder)

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.view)
        hbox = QHBoxLayout()
        self._effective_srate = QCheckBox("Use effective sampling rate")
        self._effective_srate.setChecked(True)
        hbox.addWidget(self._effective_srate)
        self._prefix_markers = QCheckBox("Prefix markers with stream ID")
        self._prefix_markers.setChecked(False)
        if not disabled:
            self._prefix_markers.setEnabled(False)
        hbox.addWidget(self._prefix_markers)
        vbox.addLayout(hbox)
        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        vbox.addWidget(self.buttonbox)
        self.buttonbox.accepted.connect(self.accept)
        self.buttonbox.rejected.connect(self.reject)

        self.resize(775, 650)
        self.view.setColumnWidth(0, 90)
        self.view.setColumnWidth(1, 200)
        self.view.setColumnWidth(2, 140)

    @property
    def effective_srate(self):
        return self._effective_srate.isChecked()

    @property
    def prefix_markers(self):
        return self._prefix_markers.isChecked()
Exemplo n.º 12
0
class Ui_tfm(object):
    def setupUi(self, tfm):
        if not tfm.objectName():
            tfm.setObjectName(u"tfm")
        tfm.resize(800, 600)
        tfm.setContextMenuPolicy(Qt.NoContextMenu)
        tfm.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.action_menu = QAction(tfm)
        self.action_menu.setObjectName(u"action_menu")
        self.action_new_dir = QAction(tfm)
        self.action_new_dir.setObjectName(u"action_new_dir")
        self.action_new_file = QAction(tfm)
        self.action_new_file.setObjectName(u"action_new_file")
        self.action_back = QAction(tfm)
        self.action_back.setObjectName(u"action_back")
        self.action_up = QAction(tfm)
        self.action_up.setObjectName(u"action_up")
        self.action_home = QAction(tfm)
        self.action_home.setObjectName(u"action_home")
        self.action_go = QAction(tfm)
        self.action_go.setObjectName(u"action_go")
        self.action_forward = QAction(tfm)
        self.action_forward.setObjectName(u"action_forward")
        self.action_copy = QAction(tfm)
        self.action_copy.setObjectName(u"action_copy")
        self.action_paste = QAction(tfm)
        self.action_paste.setObjectName(u"action_paste")
        self.action_cut = QAction(tfm)
        self.action_cut.setObjectName(u"action_cut")
        self.action_show_hidden = QAction(tfm)
        self.action_show_hidden.setObjectName(u"action_show_hidden")
        self.action_show_hidden.setCheckable(True)
        self.action_delete = QAction(tfm)
        self.action_delete.setObjectName(u"action_delete")
        self.action_rename = QAction(tfm)
        self.action_rename.setObjectName(u"action_rename")
        self.action_add_to_bookmarks = QAction(tfm)
        self.action_add_to_bookmarks.setObjectName(u"action_add_to_bookmarks")
        self.action_remove_bookmark = QAction(tfm)
        self.action_remove_bookmark.setObjectName(u"action_remove_bookmark")
        self.action_copy_path = QAction(tfm)
        self.action_copy_path.setObjectName(u"action_copy_path")
        self.action_extract_here = QAction(tfm)
        self.action_extract_here.setObjectName(u"action_extract_here")
        self.action_mount_iso = QAction(tfm)
        self.action_mount_iso.setObjectName(u"action_mount_iso")
        self.centralwidget = QWidget(tfm)
        self.centralwidget.setObjectName(u"centralwidget")
        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.vsplit = QSplitter(self.centralwidget)
        self.vsplit.setObjectName(u"vsplit")
        self.vsplit.setOrientation(Qt.Horizontal)
        self.hsplit = QSplitter(self.vsplit)
        self.hsplit.setObjectName(u"hsplit")
        self.hsplit.setOrientation(Qt.Vertical)
        self.fs_tree = QTreeView(self.hsplit)
        self.fs_tree.setObjectName(u"fs_tree")
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.fs_tree.sizePolicy().hasHeightForWidth())
        self.fs_tree.setSizePolicy(sizePolicy)
        self.fs_tree.setTabKeyNavigation(True)
        self.fs_tree.setProperty("showDropIndicator", True)
        self.fs_tree.setDragEnabled(False)
        self.fs_tree.setDragDropMode(QAbstractItemView.DropOnly)
        self.fs_tree.setDefaultDropAction(Qt.MoveAction)
        self.fs_tree.setRootIsDecorated(False)
        self.hsplit.addWidget(self.fs_tree)
        self.fs_tree.header().setVisible(False)
        self.bookmark_view = QListView(self.hsplit)
        self.bookmark_view.setObjectName(u"bookmark_view")
        self.bookmark_view.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.bookmark_view.setEditTriggers(QAbstractItemView.DoubleClicked
                                           | QAbstractItemView.EditKeyPressed
                                           | QAbstractItemView.SelectedClicked)
        self.bookmark_view.setTabKeyNavigation(True)
        self.bookmark_view.setDragDropOverwriteMode(True)
        self.bookmark_view.setDragDropMode(QAbstractItemView.DropOnly)
        self.bookmark_view.setDefaultDropAction(Qt.CopyAction)
        self.bookmark_view.setAlternatingRowColors(True)
        self.hsplit.addWidget(self.bookmark_view)
        self.mounts_view = QListView(self.hsplit)
        self.mounts_view.setObjectName(u"mounts_view")
        self.mounts_view.setTabKeyNavigation(True)
        self.mounts_view.setAlternatingRowColors(True)
        self.hsplit.addWidget(self.mounts_view)
        self.vsplit.addWidget(self.hsplit)
        self.table_view = QTableView(self.vsplit)
        self.table_view.setObjectName(u"table_view")
        sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy1.setHorizontalStretch(1)
        sizePolicy1.setVerticalStretch(0)
        sizePolicy1.setHeightForWidth(
            self.table_view.sizePolicy().hasHeightForWidth())
        self.table_view.setSizePolicy(sizePolicy1)
        self.table_view.viewport().setProperty("cursor",
                                               QCursor(Qt.ArrowCursor))
        self.table_view.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.table_view.setAcceptDrops(True)
        self.table_view.setToolTipDuration(-3)
        self.table_view.setEditTriggers(QAbstractItemView.AnyKeyPressed
                                        | QAbstractItemView.EditKeyPressed
                                        | QAbstractItemView.SelectedClicked)
        self.table_view.setDragEnabled(True)
        self.table_view.setDragDropMode(QAbstractItemView.DragDrop)
        self.table_view.setDefaultDropAction(Qt.MoveAction)
        self.table_view.setAlternatingRowColors(True)
        self.table_view.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_view.setTextElideMode(Qt.ElideMiddle)
        self.table_view.setShowGrid(False)
        self.table_view.setSortingEnabled(True)
        self.table_view.setWordWrap(False)
        self.vsplit.addWidget(self.table_view)
        self.table_view.horizontalHeader().setDefaultSectionSize(150)
        self.table_view.horizontalHeader().setHighlightSections(False)
        self.table_view.horizontalHeader().setStretchLastSection(True)
        self.table_view.verticalHeader().setVisible(False)

        self.horizontalLayout.addWidget(self.vsplit)

        tfm.setCentralWidget(self.centralwidget)
        self.statusbar = QStatusBar(tfm)
        self.statusbar.setObjectName(u"statusbar")
        self.statusbar.setContextMenuPolicy(Qt.NoContextMenu)
        self.statusbar.setSizeGripEnabled(False)
        tfm.setStatusBar(self.statusbar)
        self.toolbar = QToolBar(tfm)
        self.toolbar.setObjectName(u"toolbar")
        self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu)
        self.toolbar.setMovable(False)
        tfm.addToolBar(Qt.TopToolBarArea, self.toolbar)

        self.toolbar.addAction(self.action_back)
        self.toolbar.addAction(self.action_forward)
        self.toolbar.addAction(self.action_up)
        self.toolbar.addAction(self.action_home)
        self.toolbar.addAction(self.action_go)

        self.retranslateUi(tfm)

        QMetaObject.connectSlotsByName(tfm)

    # setupUi

    def retranslateUi(self, tfm):
        tfm.setWindowTitle(QCoreApplication.translate("tfm", u"tfm", None))
        self.action_menu.setText(
            QCoreApplication.translate("tfm", u"Menu", None))
        self.action_new_dir.setText(
            QCoreApplication.translate("tfm", u"New Directory", None))
        self.action_new_file.setText(
            QCoreApplication.translate("tfm", u"New File", None))
        self.action_back.setText(
            QCoreApplication.translate("tfm", u"Back", None))
        self.action_up.setText(QCoreApplication.translate("tfm", u"Up", None))
        self.action_home.setText(
            QCoreApplication.translate("tfm", u"Home", None))
        self.action_go.setText(QCoreApplication.translate("tfm", u"Go", None))
        #if QT_CONFIG(tooltip)
        self.action_go.setToolTip(
            QCoreApplication.translate("tfm", u"Go or Reload", None))
        #endif // QT_CONFIG(tooltip)
        self.action_forward.setText(
            QCoreApplication.translate("tfm", u"Forward", None))
        self.action_copy.setText(
            QCoreApplication.translate("tfm", u"Copy", None))
        self.action_paste.setText(
            QCoreApplication.translate("tfm", u"Paste", None))
        self.action_cut.setText(QCoreApplication.translate(
            "tfm", u"Cut", None))
        self.action_show_hidden.setText(
            QCoreApplication.translate("tfm", u"Show hidden files", None))
        #if QT_CONFIG(shortcut)
        self.action_show_hidden.setShortcut(
            QCoreApplication.translate("tfm", u"Ctrl+H", None))
        #endif // QT_CONFIG(shortcut)
        self.action_delete.setText(
            QCoreApplication.translate("tfm", u"Delete", None))
        self.action_rename.setText(
            QCoreApplication.translate("tfm", u"Rename", None))
        self.action_add_to_bookmarks.setText(
            QCoreApplication.translate("tfm", u"Add to bookmarks", None))
        self.action_remove_bookmark.setText(
            QCoreApplication.translate("tfm", u"Remove bookmark", None))
        #if QT_CONFIG(tooltip)
        self.action_remove_bookmark.setToolTip(
            QCoreApplication.translate("tfm", u"Remove bookmark", None))
        #endif // QT_CONFIG(tooltip)
        self.action_copy_path.setText(
            QCoreApplication.translate("tfm", u"Copy path", None))
        self.action_extract_here.setText(
            QCoreApplication.translate("tfm", u"Extract here", None))
        #if QT_CONFIG(tooltip)
        self.action_extract_here.setToolTip(
            QCoreApplication.translate("tfm", u"Extract here", None))
        #endif // QT_CONFIG(tooltip)
        self.action_mount_iso.setText(
            QCoreApplication.translate("tfm", u"Mount ISO", None))
        #if QT_CONFIG(tooltip)
        self.action_mount_iso.setToolTip(
            QCoreApplication.translate("tfm", u"Mount ISO", None))
Exemplo n.º 13
0
class XDFChunksDialog(QDialog):
    def __init__(self, parent, chunks, fname):
        super().__init__(parent)
        self.setWindowTitle(f"XDF Chunks ({fname})")

        self.chunks = chunks

        TAGS = {
            1: "FileHeader",
            2: "StreamHeader",
            3: "Samples",
            4: "ClockOffset",
            5: "Boundary",
            6: "StreamFooter"
        }

        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(
            ["#", "Bytes", "Tag", "Stream ID"])

        for i, chunk in enumerate(chunks, start=1):
            row = []
            row.append(_add_item(i))
            row.append(_add_item(chunk["nbytes"]))
            row.append(_add_item(f"{chunk['tag']} ({TAGS[chunk['tag']]})"))
            row.append(_add_item(chunk.get("stream_id", "")))
            self.model.appendRow(row)

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setShowGrid(False)
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.AscendingOrder)
        self.view.setEditTriggers(QTableView.NoEditTriggers)
        self.view.setFixedWidth(450)

        self.details = QPlainTextEdit("")
        self.details.setFixedWidth(450)
        self.details.setReadOnly(True)
        self.details.setTabStopDistance(30)
        font = QFont()
        font.setFamily("monospace")
        font.setStyleHint(QFont.Monospace)
        self.details.setFont(font)
        self.details.setLineWrapMode(QPlainTextEdit.NoWrap)

        hbox = QHBoxLayout()
        hbox.addWidget(self.view)
        hbox.addWidget(self.details)

        vbox = QVBoxLayout(self)
        vbox.addLayout(hbox)
        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok)
        vbox.addWidget(self.buttonbox)
        self.buttonbox.accepted.connect(self.accept)

        self.view.clicked.connect(self._update_details)

        self.setFixedSize(980, 650)
        self.view.setColumnWidth(0, 70)
        self.view.setColumnWidth(1, 80)
        self.view.setColumnWidth(2, 150)
        self.view.setColumnWidth(3, 70)

    @Slot()
    def _update_details(self):
        selection = self.view.selectionModel()
        if selection.hasSelection():
            n = int(selection.selectedIndexes()[0].data())
            self.details.setPlainText(self.chunks[n - 1].get("content", ""))
Exemplo n.º 14
0
class IncomeSpendingWidget(AbstractOperationDetails):
    def __init__(self, parent=None):
        AbstractOperationDetails.__init__(self, parent)
        self.name = "Income/Spending"

        self.details_model = None
        self.category_delegate = CategorySelectorDelegate()
        self.tag_delegate = TagSelectorDelegate()
        self.float_delegate = FloatDelegate(2)

        self.date_label = QLabel(self)
        self.details_label = QLabel(self)
        self.account_label = QLabel(self)
        self.peer_label = QLabel(self)

        self.main_label.setText(self.tr("Income / Spending"))
        self.date_label.setText(self.tr("Date/Time"))
        self.details_label.setText(self.tr("Details"))
        self.account_label.setText(self.tr("Account"))
        self.peer_label.setText(self.tr("Peer"))

        self.timestamp_editor = QDateTimeEdit(self)
        self.timestamp_editor.setCalendarPopup(True)
        self.timestamp_editor.setTimeSpec(Qt.UTC)
        self.timestamp_editor.setFixedWidth(
            self.timestamp_editor.fontMetrics().horizontalAdvance(
                "00/00/0000 00:00:00") * 1.25)
        self.timestamp_editor.setDisplayFormat("dd/MM/yyyy hh:mm:ss")
        self.account_widget = AccountSelector(self)
        self.peer_widget = PeerSelector(self)
        self.a_currency = OptionalCurrencyComboBox(self)
        self.a_currency.setText(self.tr("Paid in foreign currency:"))
        self.add_button = QPushButton(load_icon("add.png"), '', self)
        self.add_button.setToolTip(self.tr("Add detail"))
        self.del_button = QPushButton(load_icon("remove.png"), '', self)
        self.del_button.setToolTip(self.tr("Remove detail"))
        self.copy_button = QPushButton(load_icon("copy.png"), '', self)
        self.copy_button.setToolTip(self.tr("Copy detail"))
        self.details_table = QTableView(self)
        self.details_table.horizontalHeader().setFont(self.bold_font)
        self.details_table.setAlternatingRowColors(True)
        self.details_table.verticalHeader().setVisible(False)
        self.details_table.verticalHeader().setMinimumSectionSize(20)
        self.details_table.verticalHeader().setDefaultSectionSize(20)

        self.layout.addWidget(self.date_label, 1, 0, 1, 1, Qt.AlignLeft)
        self.layout.addWidget(self.details_label, 2, 0, 1, 1, Qt.AlignLeft)

        self.layout.addWidget(self.timestamp_editor, 1, 1, 1, 4)
        self.layout.addWidget(self.add_button, 2, 1, 1, 1)
        self.layout.addWidget(self.copy_button, 2, 2, 1, 1)
        self.layout.addWidget(self.del_button, 2, 3, 1, 1)

        self.layout.addWidget(self.account_label, 1, 5, 1, 1, Qt.AlignRight)
        self.layout.addWidget(self.peer_label, 2, 5, 1, 1, Qt.AlignRight)

        self.layout.addWidget(self.account_widget, 1, 6, 1, 1)
        self.layout.addWidget(self.peer_widget, 2, 6, 1, 1)

        self.layout.addWidget(self.a_currency, 1, 7, 1, 1)

        self.layout.addWidget(self.commit_button, 0, 9, 1, 1)
        self.layout.addWidget(self.revert_button, 0, 10, 1, 1)

        self.layout.addWidget(self.details_table, 4, 0, 1, 11)
        self.layout.addItem(self.horizontalSpacer, 1, 8, 1, 1)

        self.add_button.clicked.connect(self.addChild)
        self.copy_button.clicked.connect(self.copyChild)
        self.del_button.clicked.connect(self.delChild)

        super()._init_db("actions")
        self.model.beforeInsert.connect(self.before_record_insert)
        self.model.beforeUpdate.connect(self.before_record_update)
        self.mapper.setItemDelegate(IncomeSpendingWidgetDelegate(self.mapper))

        self.details_model = DetailsModel(self.details_table, db_connection())
        self.details_model.setTable("action_details")
        self.details_model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.details_table.setModel(self.details_model)
        self.details_model.dataChanged.connect(self.onDataChange)

        self.account_widget.changed.connect(self.mapper.submit)
        self.peer_widget.changed.connect(self.mapper.submit)
        self.a_currency.changed.connect(self.mapper.submit)
        self.a_currency.name_updated.connect(self.details_model.setAltCurrency)

        self.mapper.addMapping(self.timestamp_editor,
                               self.model.fieldIndex("timestamp"))
        self.mapper.addMapping(self.account_widget,
                               self.model.fieldIndex("account_id"))
        self.mapper.addMapping(self.peer_widget,
                               self.model.fieldIndex("peer_id"))
        self.mapper.addMapping(self.a_currency,
                               self.model.fieldIndex("alt_currency_id"))

        self.details_table.setItemDelegateForColumn(2, self.category_delegate)
        self.details_table.setItemDelegateForColumn(3, self.tag_delegate)
        self.details_table.setItemDelegateForColumn(4, self.float_delegate)
        self.details_table.setItemDelegateForColumn(5, self.float_delegate)

        self.model.select()
        self.details_model.select()
        self.details_model.configureView()

    def setId(self, id):
        super().setId(id)
        self.details_model.setFilter(f"action_details.pid = {id}")

    @Slot()
    def addChild(self):
        new_record = self.details_model.record()
        new_record.setNull("tag_id")
        new_record.setValue("amount", 0)
        new_record.setValue("amount_alt", 0)
        if not self.details_model.insertRecord(-1, new_record):
            logging.fatal(
                self.tr("Failed to add new record: ") +
                self.details_model.lastError().text())
            return

    @Slot()
    def copyChild(self):
        idx = self.details_table.selectionModel().selection().indexes()
        src_record = self.details_model.record(idx[0].row())
        new_record = self.details_model.record()
        new_record.setValue("category_id", src_record.value("category_id"))
        if src_record.value("tag_id"):
            new_record.setValue("tag_id", src_record.value("tag_id"))
        else:
            new_record.setNull("tag_id")
        new_record.setValue("amount", src_record.value("amount"))
        new_record.setValue("amount_alt", src_record.value("amount_alt"))
        new_record.setValue("note", src_record.value("note"))
        if not self.details_model.insertRecord(-1, new_record):
            logging.fatal(
                self.tr("Failed to add new record: ") +
                self.details_model.lastError().text())
            return

    @Slot()
    def delChild(self):
        selection = self.details_table.selectionModel().selection().indexes()
        for idx in selection:
            self.details_model.removeRow(idx.row())
            self.onDataChange(idx, idx, None)

    @Slot()
    def saveChanges(self):
        if not self.model.submitAll():
            logging.fatal(
                self.tr("Operation submit failed: ") +
                self.model.lastError().text())
            return
        pid = self.model.data(self.model.index(0, self.model.fieldIndex("id")))
        if pid is None:  # we just have saved new action record and need last inserted id
            pid = self.model.query().lastInsertId()
        for row in range(self.details_model.rowCount()):
            self.details_model.setData(
                self.details_model.index(row,
                                         self.details_model.fieldIndex("pid")),
                pid)
        if not self.details_model.submitAll():
            logging.fatal(
                self.tr("Operation details submit failed: ") +
                self.details_model.lastError().text())
            return
        self.modified = False
        self.commit_button.setEnabled(False)
        self.revert_button.setEnabled(False)
        self.dbUpdated.emit()

    @Slot()
    def revertChanges(self):
        self.model.revertAll()
        self.details_model.revertAll()
        self.modified = False
        self.commit_button.setEnabled(False)
        self.revert_button.setEnabled(False)

    def createNew(self, account_id=0):
        super().createNew(account_id)
        self.details_model.setFilter(f"action_details.pid = 0")

    def prepareNew(self, account_id):
        new_record = self.model.record()
        new_record.setNull("id")
        new_record.setValue(
            "timestamp",
            int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp()))
        new_record.setValue("account_id", account_id)
        new_record.setValue("peer_id", 0)
        new_record.setValue("alt_currency_id", None)
        return new_record

    def copyNew(self):
        old_id = self.model.record(self.mapper.currentIndex()).value(0)
        super().copyNew()
        self.details_model.setFilter(f"action_details.pid = 0")
        query = executeSQL(
            "SELECT * FROM action_details WHERE pid = :pid ORDER BY id DESC",
            [(":pid", old_id)])
        while query.next():
            new_record = query.record()
            new_record.setNull("id")
            new_record.setNull("pid")
            assert self.details_model.insertRows(0, 1)
            self.details_model.setRecord(0, new_record)

    def copyToNew(self, row):
        new_record = self.model.record(row)
        new_record.setNull("id")
        new_record.setValue(
            "timestamp",
            int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp()))
        return new_record

    def before_record_insert(self, record):
        if record.value("alt_currency_id") == 0:
            record.setNull("alt_currency_id")

    def before_record_update(self, _row, record):
        self.before_record_insert(
            record)  # processing is the same as before insert
Exemplo n.º 15
0
        """Override method from QAbstractTableModel

        Return dataframe index as vertical header data and columns as horizontal header data.
        """
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._dataframe.columns[section])

            if orientation == Qt.Vertical:
                return str(self._dataframe.index[section])

        return None


if __name__ == "__main__":

    app = QApplication(sys.argv)

    df = pd.read_csv("iris.csv")

    view = QTableView()
    view.resize(800, 500)
    view.horizontalHeader().setStretchLastSection(True)
    view.setAlternatingRowColors(True)
    view.setSelectionBehavior(QTableView.SelectRows)

    model = PandasModel(df)
    view.setModel(model)
    view.show()
    app.exec_()
Exemplo n.º 16
0
class DebugThreadsWidget(QWidget, DockContextHandler):
    def __init__(self, parent, name, data):
        if not type(data) == BinaryView:
            raise Exception('expected widget data to be a BinaryView')

        self.bv = data

        QWidget.__init__(self, parent)
        DockContextHandler.__init__(self, self, name)
        self.actionHandler = UIActionHandler()
        self.actionHandler.setupActionHandler(self)

        self.table = QTableView(self)
        self.model = DebugThreadsListModel(self.table)
        self.table.setModel(self.model)
        self.table.clicked.connect(self.threadRowClicked)

        self.item_delegate = DebugThreadsItemDelegate(self)
        self.table.setItemDelegate(self.item_delegate)

        # self.table.setSortingEnabled(True)
        self.table.setSelectionBehavior(
            QAbstractItemView.SelectionBehavior.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.table.verticalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.table.verticalHeader().setVisible(False)

        self.table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        self.table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)

        self.table.resizeColumnsToContents()
        self.table.resizeRowsToContents()
        self.table.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.table)
        self.setLayout(layout)

    def notifyOffsetChanged(self, offset):
        pass

    # called from QTableView's clicked signal
    # index: QModelIndex
    def threadRowClicked(self, index):
        index = self.model.createIndex(index.row(), 0)
        tid_str = self.model.data(index, Qt.DisplayRole)
        #print('clicked to change to thread %s' % tid_str)
        stateObj = binjaplug.get_state(self.bv)
        if stateObj.connected and not stateObj.running:
            tid = int(tid_str, 16)
            stateObj.threads.current = tid
            stateObj.ui.context_display()
            stateObj.ui.on_step()
        else:
            print('cannot set thread in current state')

    # called from plugin's context_display() function
    def notifyThreadsChanged(self, new_threads):
        idx_selected = self.model.update_rows(new_threads)
        if idx_selected:
            self.table.setCurrentIndex(idx_selected)

    def contextMenuEvent(self, event):
        self.m_contextMenuManager.show(self.m_menu, self.actionHandler)

    def shouldBeVisible(self, view_frame):
        if view_frame is None:
            return False
        else:
            return True