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

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

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

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

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

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

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

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

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

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

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

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

            self.addTab(tableView, group)
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.view = QTableView()
        self.view.horizontalHeader().hide()
        self.view.verticalHeader().hide()
        self.view.setGridStyle(Qt.NoPen)

        delegate = PreviewDelegate()
        self.view.setItemDelegate(delegate)
        self.model = PreviewModel()
        self.view.setModel(self.model)

        self.setCentralWidget(self.view)

        # Add a bunch of images.
        image_files = glob.glob("*.jpg")
        for n, fn in enumerate(image_files):
            image = QImage(fn)
            item = preview(n, fn, image)
            self.model.previews.append(item)
        self.model.layoutChanged.emit()

        self.view.resizeRowsToContents()
        self.view.resizeColumnsToContents()
class AddressWidget(QDialog):

    selectionChanged = Signal(QItemSelection)

    def __init__(self, parent=None):
        super(AddressWidget, self).__init__(parent)

        self.tableModel = TableModel()
        self.tableView = QTableView()
        self.setupTable()

        statusLabel = QLabel("Tabular data view demo")

        layout = QVBoxLayout()
        layout.addWidget(self.tableView)
        layout.addWidget(statusLabel)
        self.setLayout(layout)
        self.setWindowTitle("Address Book")
        self.resize(800,500)

        # add test data
        self.populateTestData()

    def setupTable(self):
        proxyModel = QSortFilterProxyModel(self)
        proxyModel.setSourceModel(self.tableModel)
        proxyModel.setDynamicSortFilter(True)

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

        proxyModel.setFilterKeyColumn(0)  # Filter on the "name" column
        proxyModel.sort(0, Qt.AscendingOrder)
        viewselectionmodel = self.tableView.selectionModel()
        self.tableView.selectionModel().selectionChanged.connect(self.selectionChanged)



    def populateTestData(self):
        addresses = [{"name": "John Doe", "address": "Alameda"},
                     {"name": "Alan Turing", "address": "San Deigo"},
                     {"name": "Bjarne Stroutsup", "address": "Columbia"},
                     {"name": "Herb Sutter", "address": "Seattle"},
                     {"name": "Micheal Konin", "address": "Colorado"}]

        for i in range(len(addresses)):
            self.tableModel.insertRows(0)
            ix = self.tableModel.index(0, 0, QModelIndex())
            self.tableModel.setData(ix, addresses[i]["name"], Qt.EditRole)

            ix = self.tableModel.index(0, 1, QModelIndex())
            self.tableModel.setData(ix, addresses[i]["address"], Qt.EditRole)

            self.tableView.resizeRowToContents(ix.row())
Beispiel #5
0
 def _create_table_view(self, df):
     if df is None:
         df = pd.DataFrame()
     model = PandasModel(df)
     table_view = QTableView()
     table_view.setModel(model)
     table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
     return table_view
Beispiel #6
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)
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)
Beispiel #8
0
class DebugBreakpointsWidget(QWidget, DockContextHandler):
	def __init__(self, parent, name, data):
		if not type(data) == binaryninja.binaryview.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()

		for i in range(len(self.model.columns)):
			self.table.setColumnWidth(i, self.item_delegate.sizeHint(self.table.viewOptions(), self.model.index(-1, i, QModelIndex())).width())
		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
Beispiel #9
0
    def __init__(self, crossword_index, grid_data, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle('{} {}    {}'.format(
            app_title,
            bangla.convert_english_digit_to_bangla_digit(crossword_index),
            date.today().strftime("%A, %d %B, %Y")))
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)

        tableModel = CrosswordGridModel(crossword_index, grid_data, self)
        tableView = QTableView(self)
        tableView.horizontalHeader().hide()
        tableView.verticalHeader().hide()
        tableView.setModel(tableModel)
        for i in range(grid_row_count):
            tableView.setRowHeight(i, grid_cell_size)
        for i in range(grid_column_count):
            tableView.setColumnWidth(i, grid_cell_size)
        generateIconFiles(icons_folder, tableView.columnWidth(0),
                          tableView.rowHeight(0))

        right_label = QLabel(self)
        right_pixmap = QPixmap('right_clues.png')
        right_label.setPixmap(right_pixmap)

        down_label = QLabel(self)
        down_pixmap = QPixmap('down_clues.png')
        down_label.setPixmap(down_pixmap)

        saveButton = QPushButton('Save progress', self)
        loadButton = QPushButton('Load progress', self)
        clearButton = QPushButton('Clear progress', self)
        saveButton.clicked.connect(tableModel.save_solution)
        loadButton.clicked.connect(tableModel.load_solution)
        clearButton.clicked.connect(tableModel.clear_solution)
        bbox = QDialogButtonBox(self)
        bbox.addButton(saveButton, QDialogButtonBox.AcceptRole)
        bbox.addButton(loadButton, QDialogButtonBox.AcceptRole)
        bbox.addButton(clearButton, QDialogButtonBox.AcceptRole)

        layout = QGridLayout(self)
        layout.addWidget(tableView, 0, 0)
        layout.addWidget(right_label, 0, 1, Qt.AlignLeft | Qt.AlignTop)
        layout.addWidget(down_label, 1, 0, Qt.AlignLeft | Qt.AlignTop)
        layout.addWidget(bbox, 1, 1, Qt.AlignHCenter | Qt.AlignBottom)
        self.setLayout(layout)

        windowWidth = tableView.columnWidth(
            0
        ) * grid_column_count + grid_column_count - 1 + right_clues_right - right_clues_left + layout.horizontalSpacing(
        ) + 27
        windowHeight = tableView.rowHeight(
            0
        ) * grid_row_count + grid_row_count - 1 + down_clues_bottom - down_clues_top + layout.verticalSpacing(
        ) + 10
        self.setFixedSize(QSize(windowWidth, windowHeight))
Beispiel #10
0
    def createDomainTable(self, domainmodel):

        domainTable = QTableView()
        domainTable.setModel(domainmodel)
        domainTable.setItemDelegate(DomainDelegate(domainTable))
        domainTable.verticalHeader().setVisible(False)
        domainTable.resizeColumnsToContents()
        domainTable.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        domainTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)

        return domainTable
Beispiel #11
0
class TableWidget(QWidget):
    def __init__(self, data):
        QWidget.__init__(self)

        self.model = CustomTableModel(data)

        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.table_view.setMinimumSize(400, 600)

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

        self.init_data()

        self.chart.createDefaultAxes()
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setMinimumSize(800, 600)

        # 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, 2)
        self.main_layout.setColumnStretch(0, 1)
        self.setLayout(self.main_layout)

    def add_series(self, name, columns):
        self.series = QtCharts.QLineSeries()
        self.series.setName(name)
        self.mapper = QtCharts.QVXYModelMapper(self)
        self.mapper.setXColumn(columns[0])
        self.mapper.setYColumn(columns[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(columns[0], 0, 2, self.model.rowCount()))

    def init_data(self):
        for i in range(int(self.model.columnCount()/2)):
            self.add_series("Line {}".format(i+1), [i*2, (i*2)+1])
class nDisplayMonitorUI(QtWidgets.QWidget):

    def __init__(self, parent, monitor):
        QtWidgets.QWidget.__init__(self, parent)

        # create buttons
        #
        self.btnForceFocus = QPushButton("Force Focus")
        self.btnForceFocus.setToolTip("Forces focus on the nDisplay window")
        self.btnForceFocus.clicked.connect(monitor.btnForceFocus_clicked)

        self.btnFixExeFlags = QPushButton("Fix ExeFlags")
        self.btnFixExeFlags.setToolTip("Disables fullscreen optimizations on the executable.")
        self.btnFixExeFlags.clicked.connect(monitor.btnFixExeFlags_clicked)

        self.btnSoftKill = QPushButton("Soft Kill")
        self.btnSoftKill.setToolTip(
            "Sends a message to the master node to terminate the session.\n"
            "This is preferable to the normal kill button because it ensures the nodes exit properly")
        self.btnSoftKill.clicked.connect(monitor.btnSoftKill_clicked)

        # arrange them in a horizontal layout
        layout_buttons = QHBoxLayout()
        layout_buttons.addStretch()
        layout_buttons.addWidget(self.btnForceFocus)
        layout_buttons.addWidget(self.btnFixExeFlags)
        layout_buttons.addWidget(self.btnSoftKill)

        # create table
        #
        self.tableview = QTableView()
        self.tableview.setModel(monitor) # the monitor is the model of this tableview.

        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size.setHorizontalStretch(1)
        self.tableview.setSizePolicy(size)

        # configure resize modes on headers
        self.tableview.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableview.horizontalHeader().setStretchLastSection(False)
        self.tableview.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableview.verticalHeader().setVisible(False)

        # create layout
        #
        layout = QVBoxLayout()

        layout.addLayout(layout_buttons)
        layout.addWidget(self.tableview)

        self.setLayout(layout)
Beispiel #13
0
class Widget(QWidget):
    def __init__(self, data):
        QWidget.__init__(self)

        #Getting the Model
        self.model = CustomTableModel(data)

        #Creating a QTableView
        self.table_view = QTableView()
        self.table_view.setModel(self.model)

        #QTableView Headers
        self.horizontal_header = self.table_view.horizontalHeader()
        self.vertical_header = self.table_view.verticalHeader()
        self.horizontal_header.setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
        self.horizontal_header.setStretchLastSection(True)

        #QWidget Layout
        self.main_layout = QHBoxLayout()
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        #Left Layout
        size.setHorizontalStretch(1)
        self.table_view.setSizePolicy(size)
        self.main_layout.addWidget(self.table_view)

        # Set layout to QWidget
        self.setLayout(self.main_layout)
Beispiel #14
0
class widget(QWidget):
    def __init__(self, data):
        QWidget.__init__(self)

        self.model = CustomTableModel(data)

        self.table_view = QTableView()
        self.table_view.setModel(self.model)

        self.horizontal_header = self.table_view.horizontalHeader()
        self.vertical_header = self.table_view.verticalHeader()
        self.horizontal_header.setSectionResizeMode(
            QHeaderView.ResizeToContents)

        self.vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)

        self.horizontal_header.setStretchLastSection(True)

        self.main_layout = QHBoxLayout()
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        size.setHorizontalStretch(1)
        self.table_view.setSizePolicy(size)
        self.main_layout.addWidget(self.table_view)

        self.setLayout(self.main_layout)
Beispiel #15
0
class QDataFrame(QWidget):
    def __init__(self, df=None, parent=None):
        QWidget.__init__(self, parent)
        self.df = df

        self.model = QDataFrameTableModel(self.df)

        self.table_view = QTableView()
        self.table_view.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        #self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        #self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.table_view.setModel(self.model)

        self.main_layout = QHBoxLayout()
        self.main_layout.addWidget(self.table_view)
        self.setLayout(self.main_layout)
Beispiel #16
0
class DisplayPerformanceData(QWidget):
    def __init__(self, parent=None):
        super(DisplayPerformanceData, self).__init__(parent)

        self.model = QStandardItemModel(self)

        self.tableView = QTableView(self)
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setStretchLastSection(True)

        self.layoutVertical = QVBoxLayout(self)
        self.layoutVertical.addWidget(self.tableView)

    def loadCsv(self, fileName):
        with open(fileName, "r") as fileInput:
            for row in csv.reader(fileInput):
                items = [QStandardItem(field) for field in row]
                self.model.appendRow(items)
Beispiel #17
0
class ScoresWidget(QDockWidget):
    """Widget that display a solution scores."""
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setWindowTitle("Scores")

        # Build widgets
        self.search_field = QLineEdit(self)
        self.checkbox_positive = QCheckBox("Positive", self)
        self.checkbox_positive.setChecked(True)
        self.checkbox_negative = QCheckBox("Negative", self)
        self.checkbox_negative.setChecked(True)
        self.checkbox_neutral = QCheckBox("Neutral", self)
        self.table = QTableView(self)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.verticalHeader().setVisible(False)

        # Build layout
        layout_header = QHBoxLayout()
        layout_header.addWidget(self.search_field)
        layout_header.addWidget(self.checkbox_positive)
        layout_header.addWidget(self.checkbox_negative)
        layout_header.addWidget(self.checkbox_neutral)

        layout_main = QVBoxLayout()
        layout_main.addLayout(layout_header)
        layout_main.addWidget(self.table)

        main_widget = QWidget(self)
        main_widget.setLayout(layout_main)
        self.setWidget(main_widget)

        # Configure models
        self.model = PointsTableModel(self)
        self._proxy_model = ScoreProxyModel()
        self._proxy_model.setSourceModel(self.model)
        self._proxy_model.sort(
            1, Qt.AscendingOrder)  # sort by lowest score by default

        # Configure table
        self.table.setModel(self._proxy_model)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # Connect signals
        for signal, callback in (
            (self.search_field.textChanged,
             self._proxy_model.setFilterWildcard),
            (self.checkbox_positive.stateChanged,
             self._proxy_model.set_positive),
            (self.checkbox_negative.stateChanged,
             self._proxy_model.set_negative),
            (self.checkbox_neutral.stateChanged,
             self._proxy_model.set_neutral),
        ):
            signal.connect(callback)
Beispiel #18
0
    def _create_device_table(self) -> QTableView:
        device_table = QTableView()
        device_table.setModel(self._device_model)
        device_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        device_table.setSelectionMode(QAbstractItemView.SingleSelection)

        device_table.selectionModel().selectionChanged.connect(
            self._on_device_table_selection_changed)

        horizontal_header = device_table.horizontalHeader()
        vertical_header = device_table.verticalHeader()
        horizontal_header.setSectionResizeMode(QHeaderView.ResizeToContents)
        vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
        horizontal_header.setStretchLastSection(True)

        return device_table
Beispiel #19
0
class Widget(QWidget):
    def __init__(self, data):
        QWidget.__init__(self)

        # Getting the Model
        self.model = CustomTableModel(data)

        # Creating a QTableView
        self.table_view = QTableView()
        self.table_view.setModel(self.model)

        # QTableView Headers
        self.horizontal_header = self.table_view.horizontalHeader()
        self.vertical_header = self.table_view.verticalHeader()
        self.horizontal_header.setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
        self.horizontal_header.setStretchLastSection(True)

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

        # Creating QChartView
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)

        # QWidget Layout
        self.main_layout = QHBoxLayout()
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        ## Left layout
        size.setHorizontalStretch(1)
        self.table_view.setSizePolicy(size)
        self.main_layout.addWidget(self.table_view)

        ## Right Layout
        size.setHorizontalStretch(4)
        self.chart_view.setSizePolicy(size)
        self.main_layout.addWidget(self.chart_view)

        # Set the layout to the QWidget
        self.setLayout(self.main_layout)
Beispiel #20
0
    def create_view(cls, deck) -> "WeaponDeckView":
        obj = cls(deck)
        obj.weapon_widget = QWidget()
        weapon_layout = QHBoxLayout()
        obj.weapon_widget.setLayout(weapon_layout)

        table_view = QTableView()
        table_view.setModel(obj)
        # noinspection PyTypeChecker
        obj.connect(table_view, SIGNAL('doubleClicked(QModelIndex)'),
                    obj.cell_double_clicked)

        h_header = table_view.horizontalHeader()
        for i in range(1, obj.columnCount()):
            h_header.setSectionResizeMode(i, QHeaderView.ResizeToContents)
        h_header.setSectionResizeMode(0, QHeaderView.Stretch)

        weapon_layout.addWidget(table_view)

        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size.setHorizontalStretch(1)
        obj.weapon_widget.setSizePolicy(size)

        return obj
class FieldNameListEditor(QWidget):
    """A widget to edit foreign keys' field name lists."""

    data_committed = Signal(name="data_committed")

    def __init__(self, parent, option, index):
        """Initialize class."""
        super().__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self.model = MinimalTableModel(self)
        self.model.flags = self.model_flags
        self.view = QTableView(self)
        self.view.setModel(self.model)
        self.view.verticalHeader().hide()
        self.view.horizontalHeader().hide()
        self.view.setShowGrid(False)
        check_box_delegate = CheckBoxDelegate(self)
        self.view.setItemDelegateForColumn(0, check_box_delegate)
        check_box_delegate.data_committed.connect(
            self._handle_check_box_data_committed)
        self.button = QPushButton("Ok", self)
        self.button.setFlat(True)
        self.view.verticalHeader().setDefaultSectionSize(option.rect.height())
        self.button.setFixedHeight(option.rect.height())
        layout.addWidget(self.view)
        layout.addWidget(self.button)
        self.button.clicked.connect(self._handle_ok_button_clicked)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)
        x_offset = parent.parent().columnViewportPosition(index.column())
        y_offset = parent.parent().rowViewportPosition(index.row())
        self.position = parent.mapToGlobal(QPoint(0, 0)) + QPoint(
            x_offset, y_offset)

    def model_flags(self, index):
        """Return index flags."""
        if not index.isValid():
            return Qt.NoItemFlags
        if index.column() != 0:
            return ~Qt.ItemIsEditable
        return Qt.ItemIsEditable

    @Slot("QModelIndex", name="_handle_check_box_data_committed")
    def _handle_check_box_data_committed(self, index):
        """Called when checkbox delegate wants to edit data. Toggle the index's value."""
        data = index.data(Qt.EditRole)
        self.model.setData(index, not data)

    @Slot("bool", name="_handle_ok_button_clicked")
    def _handle_ok_button_clicked(self, checked=False):
        """Called when user pressed Ok."""
        self.data_committed.emit()

    def set_data(self, field_names, current_field_names):
        """Set values to show in the 'menu'. Reset model using those values and update geometry."""
        data = [[name in current_field_names, name] for name in field_names]
        self.model.reset_model(data)
        self.view.resizeColumnsToContents()
        width = self.view.horizontalHeader().length() + qApp.style(
        ).pixelMetric(QStyle.PM_ScrollBarExtent)
        self.setFixedWidth(width + 2)
        height = self.view.verticalHeader().length() + self.button.height()
        parent_height = self.parent().height()
        self.setFixedHeight(min(height, parent_height / 2) + 2)
        self.move(self.position)

    def data(self):
        return ",".join(
            [name for checked, name in self.model._main_data if checked])
Beispiel #22
0
 def set_control(self, control: QtWidgets.QTableView):
     """Called by the GUI to associate a TableView control with this instance.  Sets up column widths and stores a
     reference for adjusting the widths later."""
     self.control = control
     for index, column in enumerate(self.columns):
         control.horizontalHeader().setSectionResizeMode(index, column.size)
Beispiel #23
0
class MetricsDialog(PluginDialog):

    ENABLE = True

    def __init__(self, conn=None, parent=None):
        super().__init__(parent)
        self.conn = conn

        self.view = QTableView()
        self.model = MetricModel()
        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok)

        self.view.setModel(self.model)
        self.view.setAlternatingRowColors(True)
        self.view.horizontalHeader().hide()
        self.view.verticalHeader().hide()
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.buttons.accepted.connect(self.accept)

        self.setWindowTitle(self.tr("Project metrics"))

        v_layout = QVBoxLayout()
        v_layout.addWidget(self.view)
        v_layout.addWidget(self.buttons)
        self.setLayout(v_layout)

        # Async stuff
        self.metrics_runnable = None
        self.populate()

    def populate(self):
        """Async implementation to populate the view

        Notes:
            When closing the dialog window, the thread is not stopped.
        """
        def compute_metrics(conn):
            """Async function"""
            return {
                "variants": get_variant_count(conn),
                "snps": get_snp_count(conn),
                "transitions": get_variant_transition(conn),
                "transversions": get_variant_transversion(conn),
                "samples": get_sample_count(conn),
            }

        self.model.add_metrics(self.tr("Loading..."), self.tr("data..."))

        self.metrics_runnable = SqlRunnable(self.conn, compute_metrics)
        self.metrics_runnable.finished.connect(self.loaded)
        QThreadPool.globalInstance().start(self.metrics_runnable)

    def loaded(self):
        """Called at the end of the thread and populate data"""
        results = self.metrics_runnable.results

        self.model.clear()
        ratio = results["transitions"] / results["transversions"]

        self.model.add_metrics("Variant count", results["variants"])
        self.model.add_metrics("Snp count", results["snps"])
        self.model.add_metrics("Transition count", results["transitions"])
        self.model.add_metrics("Transversion count", results["transversions"])
        self.model.add_metrics("Tr/tv ratio", ratio)
        self.model.add_metrics("Sample count", results["variants"])

        self.view.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.ResizeToContents)
        self.view.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)
class ConfigureUsersDialog(QDialog):
    def __init__(self, users):
        super().__init__()
        self.setWindowTitle("Configure Users")
        self.model = TableModel(users)

        self.layout = QVBoxLayout()
        self.table_layout = QHBoxLayout()
        self.users_table = QTableView()
        self.users_table.setModel(self.model)
        self.users_table.horizontalHeader().setStretchLastSection(True)
        self.table_layout.addWidget(self.users_table)

        self.table_buttons_layout = QVBoxLayout()
        self.add_user_button = QPushButton()
        self.add_user_button.setText("Add User")
        self.add_user_button.clicked.connect(self._add_user_clicked)
        self.delete_user_button = QPushButton()
        self.delete_user_button.setText("Delete User")
        self.delete_user_button.clicked.connect(self._delete_user_clicked)
        self.table_buttons_layout.addSpacerItem(
            QSpacerItem(0, 0, vData=QSizePolicy.Expanding))
        self.table_buttons_layout.addWidget(self.add_user_button)
        self.table_buttons_layout.addWidget(self.delete_user_button)
        self.table_buttons_layout.addSpacerItem(
            QSpacerItem(0, 0, vData=QSizePolicy.Expanding))
        self.table_layout.addLayout(self.table_buttons_layout)

        self.layout.addLayout(self.table_layout)

        self.error_text = QLabel()
        self.error_text.setStyleSheet("color: red;")
        self.layout.addWidget(self.error_text)

        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                           | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._on_accepted_clicked)
        self.button_box.rejected.connect(self.reject)
        self.layout.addWidget(self.button_box)
        self.setLayout(self.layout)

        self.resize(600, 400)

    def _on_accepted_clicked(self):
        self._complete_table()
        if not self.model.are_users_unique():
            self.error_text.setText("Name must be unique for each user")
            return

        self.error_text.setText("")
        self.accept()

    def _complete_table(self):
        # The currently selected cell only updates the model when 'return' is
        # pressed or another cell is selected. If the user is updating a value
        # then clicks 'OK' without pressing 'return' then the change is lost.
        # This is a Qt thing - the workaround is to take focus from the table.
        self.button_box.button(self.button_box.Ok).setFocus()

    def _add_user_clicked(self):
        self.users_table.model().insertRow(self.model.num_rows)

    def _delete_user_clicked(self):
        rows_to_remove = set()
        for index in self.users_table.selectedIndexes():
            rows_to_remove.add(index.row())
        self.users_table.model().removeRows(list(rows_to_remove))

    def get_users(self):
        return self.model.users
Beispiel #25
0
class Widget(QWidget):
    """ Класс QWidget является базовым для всех объектов пользовательского интерфейса
    Виджет - это элементарный объект пользовательского интерфейса:
    он получает события мыши, клавиатуры и другие события от оконной системы и рисует свое изображение на экране.
    """
    def __init__(self, data, splineChartData, areaChartData, scatterChartData,
                 pieChartData, bwChartData, candlestickChartData):
        QWidget.__init__(self)
        """ получение модели """
        self.model = CustomTableModel(data)
        """переходим в класс CustomTableModel и создаем объект-таблицу, model-часть класса с помощью которого работаем с данными,имя поля-model  """
        self.table_view = QTableView()
        """полностью устраивает класс  QTableView поэтому доп конструкторов и ф-ций не пишем, а просто создаем и он поле нашего класса, имя поля-table_view  """
        self.table_view.setModel(self.model)
        """может рисовать таблицу в соотвествие с полученными данными(3 столбца, нужные числа и тд) """
        resize = QHeaderView.ResizeToContents
        """ Класс QHeaderView предоставляет строку заголовка или столбец заголовка для представлений элементов, заголовок маштабируется """
        self.horizontal_header = self.table_view.horizontalHeader()

        self.vertical_header = self.table_view.verticalHeader()

        self.horizontal_header.setSectionResizeMode(resize)

        self.vertical_header.setSectionResizeMode(resize)

        self.horizontal_header.setStretchLastSection(True)
        """ Формируется данные для рисования заголовка  """
        """создание графика 
        модуль QtChart предоставляет множество типов графиков и опций для графического представления данных. 
        """

        chart1 = QtCharts.QChart()
        """нас устраивает класс QChart полностью, доп методы и консрукторы не нужны """
        chart1.setAnimationOptions(QtCharts.QChart.AllAnimations)
        """ установить параметры анимации, запускается рисование """
        self.add_series("Значение", [0, 1], chart1)
        """подготовка вкладки на кот размещена диаграмма """
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size.setHorizontalStretch(4)
        #-----------------------------------------
        chart_view1 = QtCharts.QChartView(chart1)
        """подготовка визуализации продолжается """
        chart_view1.setRenderHint(QPainter.Antialiasing)

        #self.chart_view1.setSizePolicy(size)
        minWidth = 400
        chart_view1.setMinimumWidth(minWidth)

        #-----------------------------------------------------
        chart2 = QtCharts.QChart()
        chart2.setAnimationOptions(QtCharts.QChart.AllAnimations)
        self.add_series("Глубина", [0, 2], chart2)  #данные для каждого графика
        chart_view2 = QtCharts.QChartView(chart2)
        """подготовка визуализации продолжается """
        chart_view2.setRenderHint(QPainter.Antialiasing)
        """ QWidget расположение """
        """ правое расположение """
        #self.chart_view2.setSizePolicy(size)
        chart_view2.setMinimumWidth(minWidth)

        main_layout = QHBoxLayout()
        splitter = QSplitter()

        dateColumn = 0
        magColumn = 1
        depthsColumn = 2

        xDates = self.getDateAsCategoricalColumn(dateColumn)
        yMagnitudes = self.getFloatColumn(magColumn)
        yDepths = self.getFloatColumn(depthsColumn)

        # print("ymags")
        # print(yMagnitudes)
        # print("ydepths")
        # print(yDepths)

        bc1 = self.createBarCharts(xDates, yMagnitudes, yDepths)
        bar1ChartView = QtCharts.QChartView(bc1)
        bar1ChartView.setRenderHint(QPainter.Antialiasing)

        chartViewsHbox = QHBoxLayout()
        chartViewsHbox.addWidget(chart_view1)
        chartViewsHbox.addWidget(chart_view2)

        vbox = QVBoxLayout()
        vbox.addLayout(chartViewsHbox)
        vbox.addWidget(bar1ChartView)

        vboxWidget = QWidget()
        vboxWidget.setLayout(vbox)
        splitter.addWidget(vboxWidget)

        splitter.addWidget(self.table_view)

        main_layout.addWidget(splitter)

        # self.setLayout(main_layout) # установить макет на QWidget """

        mainWidget = QWidget()
        mainWidget.setLayout(main_layout)

        tabWidget = QTabWidget()

        tabWidget.addTab(mainWidget, "travis scott")

        splineTab = ddv.charts.createSplineChart(splineChartData)
        tabWidget.addTab(splineTab, "spline chart")

        #areaTab = ddv.charts.createAreaChart(areaChartData)
        #tabWidget.addTab(areaTab, "area chart")

        scatterTab = ddv.charts.createScatterChart(scatterChartData)
        tabWidget.addTab(scatterTab, "scatter chart")

        pieTab = ddv.charts.createPieChart(pieChartData)
        tabWidget.addTab(pieTab, "pie chart")

        bwTab = ddv.charts.createBwChart(bwChartData)
        tabWidget.addTab(bwTab, "b w chart")

        candlestickTab = ddv.charts.createCandlestickChart(
            candlestickChartData)
        tabWidget.addTab(candlestickTab, "candlestick chart")

        grid = QGridLayout()
        grid.addWidget(tabWidget)

        #grid.addWidget(areaTab)

        self.setLayout(grid)
        """ левое расположение """
        size.setHorizontalStretch(1)
        self.table_view.setSizePolicy(size)

    def createBarCharts(self, x, y1, y2):
        barSet1 = QtCharts.QBarSet("Magnitude")
        # c1 = PySide2.QtWidgets.QColorDialog.getColor()
        barSet1.setColor(Qt.white)
        barSet1.append(y1)

        barSet2 = QtCharts.QBarSet("Depths")
        barSet2.setColor(Qt.magenta)
        barSet2.append(y2)

        barSeries1 = QtCharts.QBarSeries()
        barSeries1.append(barSet1)
        barSeries1.append(barSet2)

        barChart1 = QtCharts.QChart()
        barChart1.addSeries(barSeries1)
        barChart1.setTitle("my first bar chart")
        barChart1.setAnimationOptions(QtCharts.QChart.SeriesAnimations)

        categories = x
        barCategoryAxis = QtCharts.QBarCategoryAxis()
        barCategoryAxis.append(categories)
        barChart1.createDefaultAxes()
        barChart1.setAxisX(barCategoryAxis, barSeries1)

        barChart1.legend().setVisible(True)
        barChart1.legend().setAlignment(Qt.AlignTop)

        return barChart1

    def getFloatColumn(self, column):

        res = []

        for i in range(self.model.rowCount()):
            # print("checking the data...", i, self.model.index(i, column).data())

            y = float(self.model.index(i, column).data())
            res.append(y)

        return res

    def getDateAsCategoricalColumn(self, column):

        res = []

        for i in range(self.model.rowCount()):
            t = self.model.index(i, column).data()
            date_fmt = "yyyy-MM-dd HH:mm:ss.zzz"
            #outDateFormat = "dd.MM.yyyy (h:mm)"
            outDateFormat = date_fmt

            # x = float(QDateTime().fromString(t, date_fmt).toMSecsSinceEpoch())
            x = QDateTime().fromString(t, date_fmt).toString(outDateFormat)
            res.append(x)

            # y = float(self.model.index(i, columns[1]).data())

            # потому что сложно рисовать график с минусовой осью ???
            # if x > 0 and y > 0:
            # self.series.append(x, y)

        return res

    def add_series(
        self, name, columns, chart
    ):  #выходит add.series так написан что по Ох автоматически будет дата?
        """ Формирует название оси """
        self.series = QtCharts.QLineSeries()
        self.series.setName(name)
        """ формирует 1 массив series из 2 столбцов, добавляя в него данные из Х и У """
        for i in range(self.model.rowCount()):
            """ получение даты """
            t = self.model.index(i, 0).data(
            )  #типа нулевой столбец(дата) и в нем по строкам  будем переходить с помощью цикла этого
            date_fmt = "yyyy-MM-dd HH:mm:ss.zzz"  #но вообще тут уже прописано как бы что в нулевом столбце будет дата

            #x = QDateTime().fromString(t, date_fmt).toSecsSinceEpoch()
            x = float(QDateTime().fromString(t, date_fmt).toMSecsSinceEpoch())
            #x = QDateTime().fromString("2019-01-01 12:00:00.100", date_fmt).toMSecsSinceEpoch()

            # не работает:
            # QLineSeries.append(x, y) ждёт float-ов, а не QDateTime()
            # x = QDateTime().fromString(t, date_fmt)

            y = float(self.model.index(i, columns[1]).data())

            # print(x, y)

            # потому что сложно рисовать график с минусовой осью ???
            if x > 0 and y > 0:
                self.series.append(x, y)

        chart.addSeries(self.series)
        """ задание оси X """
        #self.axis_x = QtCharts.QDateTimeAxis()
        self.axis_x = QtCharts.QValueAxis()
        """ Класс QDateTimeAxis добавляет даты и время к оси диаграммы. """
        self.axis_x.setTickCount(6)
        """setTickCounе( int count ) устанавливает количество отметок на оси для подсчета, на оси Х будет 10 штрихов """
        #self.axis_x.setFormat("dd.MM.yy hh:mm:ss")
        """ setFormat - задаёт формат вывод текстового представления значения. """
        self.axis_x.setTitleText("Дата")
        chart.addAxis(self.axis_x, Qt.AlignBottom)
        """ Добавляет ось оси к диаграмме, выровненной, как указано выравниванием. """
        self.series.attachAxis(self.axis_x)
        """ Возвращает, true если ось была успешно присоединена, false в противном случае. """
        """ задание оси Y """
        self.axis_y = QtCharts.QValueAxis()
        """ Класс QValueAxis добавляет значения к осям диаграммы. """
        self.axis_y.setTickCount(6)
        """ Свойство setTickCount содержит количество отметок на оси. Это указывает, сколько линий сетки нарисовано на графике. """
        self.axis_y.setLabelFormat("%.2f")
        """ Свойство setLabelFormat содержит формат метки оси. """
        self.axis_y.setTitleText(
            name
        )  #изменила название оси, что ифами написать, как обратиться к имени той колонки которую я в параметры передаю?
        chart.addAxis(self.axis_y, Qt.AlignLeft)
        self.series.attachAxis(self.axis_y)
        """ получение цвета из QC  hart для использования в QTableView, будет выделять столбец таблицы тем же цветом что и линия в диарамме!! """
        self.model.color = "{}".format(self.series.pen().color().name())
Beispiel #26
0
class Form(QMainWindow):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.svg_style = SvgStyle()

        self.temp_svg_file = QTemporaryFile()
        if not self.temp_svg_file.open():  # need to obtain temp file name
            raise RuntimeError('Cannot create temporary file for svg object')
        self.temp_svg_file.close()

        self.setWindowTitle(u'Круговая диаграмма')

        self.model = CustomTableModel()
        self.table_view = QTableView()
        self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.table_view.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

        self.widget_svg = QSvgWidget()
        self.widget_style = StyleWidget()
        self.widget_style.style_changed.connect(self.style_updated)

        # central widget layout
        layout = QHBoxLayout()
        # size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        # size.setHorizontalStretch(1)
        # self.table_view.setSizePolicy(size)
        layout.addWidget(self.table_view)
        layout.addWidget(self.widget_svg)
        layout.addWidget(self.widget_style)

        self.widget_svg.setFixedSize(500, 500)

        widget_central = QWidget()
        widget_central.setLayout(layout)

        self.setCentralWidget(widget_central)

        # main menu
        self.menu = self.menuBar()
        self.menu_file = self.menu.addMenu("File")

        # load QAction
        action_load = QAction('Open', self)
        action_load.setShortcut(QKeySequence.Open)
        action_load.triggered.connect(self.load_data)
        self.menu_file.addAction(action_load)

        self.statusBar()

        # exit QAction
        action_exit = QAction('Exit', self)
        action_exit.setShortcut(QKeySequence.Quit)
        action_exit.triggered.connect(self.close)
        self.menu_file.addAction(action_exit)

        # window dimensions
        # geometry = qApp.desktop().availableGeometry(self)
        # self.setFixedSize(geometry.width() * 0.5, geometry.height() * 0.5)

    def load_data(self) -> None:
        filename, _ = QFileDialog.getOpenFileName(self, "Load data", dir="./tests",
                                                  filter="Text files (*.txt);;Excel data (*csv)")
        if filename:
            country_data: CountryData = read_data(filename)
            self.model = CustomTableModel(country_data)
            self.table_view.setModel(self.model)
            self.statusBar().showMessage("Data loaded and plotted")
            self.draw_diagram()

    def load_svg(self, filename) -> None:
        self.widget_svg.load(filename)

    def draw_diagram(self) -> None:
        n_countries: int = self.model.rowCount()
        if n_countries > 0:
            style: SvgStyle = self.svg_style
            delta_angle: float = 2.0*math.pi/n_countries
            max_value: float = max(self.model.values)
            dwg = Drawing(self.temp_svg_file.fileName(), profile='tiny', viewBox='-250 -250 500 500')
            for idx, v in enumerate(self.model.values):
                x: float = style.line_length * v/max_value * math.sin(idx * delta_angle)
                y: float = -style.line_length * v/max_value * math.cos(idx * delta_angle)
                dwg.add(shapes.Line(start=(0, 0), end=(x, y),
                                    stroke=style.line_color, stroke_width=style.line_width))
                radius: float = style.circle_rad
                if style.circle_rad_normalization:
                    radius *= v/max_value
                dwg.add(shapes.Circle(center=(x, y), r=radius,
                                      stroke=style.circle_stroke_color, stroke_width=style.circle_stroke_width,
                                      fill=style.circle_fill_color))
            dwg.save(pretty=True)
            self.load_svg(self.temp_svg_file.fileName())

    @Slot()
    def style_updated(self, style: SvgStyle):
        self.svg_style = style
        self.draw_diagram()
Beispiel #27
0
class MainForm(QDialog):
    def __init__(self, datalist, header, parent=None):
        super(MainForm, self).__init__(parent)
        self.setWindowTitle("Raio-X do Orçamento Helper")
        self.setMinimumSize(800, 600)
        self.year_label = QLabel("Ano")
        self.year_input = QLineEdit("2019")

        self.selection_button = QPushButton("Selecionar pasta")
        self.selection_button.clicked.connect(self.select_folder)

        self.update_button = QPushButton("Atualizar Dados")
        self.update_button.clicked.connect(self.update)

        self.folder_address_input = QLineEdit(".")

        layout = QVBoxLayout()
        # layout.addWidget(self.year_label)
        layout.addWidget(self.year_input)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.selection_button)
        hlayout.addWidget(self.folder_address_input)
        layout.addLayout(hlayout)

        # tabela
        self.datalist = datalist
        self.table_model = UnitTableModel(self, datalist, header)
        self.table_view = QTableView()
        #self.table_view.setSelectionMode(QAbstractItemView.SingleSelection)
        # self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_view.setModel(self.table_model)
        # bind cell click to a method reference
        # self.table_view.clicked.connect(self.showSelection)
        # self.table_view.clicked.connect(self.selectRow)
        # enable sorting
        # self.table_view.setSortingEnabled(True)
        self.resize_header()
        layout.addWidget(self.table_view)
        layout.addWidget(self.update_button)
        self.setLayout(layout)

    def resize_header(self):
        header = self.table_view.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)

    def showSelection(self, item):
        cellContent = item.data()
        # print(cellContent)  # test
        sf = "You clicked on {}".format(cellContent)
        # display in title bar for convenience
        self.setWindowTitle(sf)

    def update_model(self, folder):
        filenames = os.listdir(folder)
        self.datalist = [(unit, nearest(unit, filenames), QCheckBox())
                         for unit in data.units]
        self.table_model = UnitTableModel(self, self.datalist, HEADER)
        self.table_view.setModel(self.table_model)
        self.table_view.update()

    def select_folder(self):
        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.Directory)
        if dialog.exec_():
            selected_dir = dialog.selectedFiles()[0]
            self.folder_address_input.setText(selected_dir)
            self.update_model(selected_dir)

    def compress_files(self):
        files_dir = self.folder_address_input.text()
        for row in self.datalist:
            print("Compressing file {}".format(row[1]))
            compressfile(os.path.join(files_dir, row[1]),
                         os.path.join(files_dir, row[0]))

    def upload_files(self):
        files_dir = self.folder_address_input.text()
        for count, row in enumerate(self.datalist):
            print("Uploading file {}".format(row[0]))
            # TODO: read year from UI (combobox?)
            upload_sheet(os.path.join(files_dir, row[0]), 2019)
            self.table_model.update_row_status(count, Status.SENT)
        print("Files uploaded")

    def update(self):
        print("Updating files")
        self.compress_files()
        self.upload_files()
        print("Update completed")
Beispiel #28
0
class _ExtractSeriesWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # {series name: {frame name: [ (Attribute, QPersistentModelIndex) ]
        self.seriesOptions: Dict[str, Dict[str, List[Tuple[
            int, QPersistentModelIndex]]]] = dict()
        # {frame name: attribute model}
        self.models: Dict[str, CustomProxyAttributeModel] = dict()
        self.seriesView = CustomSignalView(parent=self)
        self.seriesModel = CustomStringListModel(self)
        self.seriesModel.setHeaderLabel('Series name')
        self.addSeriesButton = QPushButton('Add', self)
        self.removeSeriesButton = QPushButton('Remove', self)
        self.addSeriesButton.clicked.connect(self.addSeries)
        self.removeSeriesButton.clicked.connect(self.removeSeries)
        self.seriesView.setModel(self.seriesModel)
        self.seriesView.setDragDropMode(QTableView.InternalMove)
        self.seriesView.setDragDropOverwriteMode(False)
        self.seriesView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.seriesView.verticalHeader().hide()

        # Connect selection to change
        self.seriesView.selectedRowChanged[str, str].connect(
            self.onSeriesSelectionChanged)
        # When a series is added it should be immediately edited
        self.seriesModel.rowAppended.connect(self.editSeriesName)
        self.seriesModel.rowsInserted.connect(self.checkNoSeries)
        self.seriesModel.rowsRemoved.connect(self.checkNoSeries)

        self.workbenchView = WorkbenchView(self, editable=False)
        self.workbench: WorkbenchModel = None
        self.workbenchView.selectedRowChanged[str, str].connect(
            self.onFrameSelectionChanged)

        self.attributesView = SearchableAttributeTableWidget(
            self, True, False, False, [Types.Numeric, Types.Ordinal])

        firstRowLayout = QHBoxLayout()
        firstRowLayout.setSpacing(5)

        selectionGroup = QGroupBox(
            title=
            'Select a time series. Then select the columns to add from the current '
            'datasets',
            parent=self)
        firstRowLayout.addWidget(self.seriesView)
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.addSeriesButton)
        buttonLayout.addWidget(self.removeSeriesButton)
        firstRowLayout.addLayout(buttonLayout)
        firstRowLayout.addSpacing(30)
        firstRowLayout.addWidget(self.workbenchView)
        firstRowLayout.addSpacing(30)
        firstRowLayout.addWidget(self.attributesView)
        selectionGroup.setLayout(firstRowLayout)

        # Time axis labels model with add/remove buttons
        self.timeAxisModel = CustomStringListModel(self)
        self.timeAxisModel.setHeaderLabel('Time labels')
        self.timeAxisView = CustomSignalView(self)
        self.timeAxisView.setModel(self.timeAxisModel)
        self.addTimeButton = QPushButton('Add', self)
        self.removeTimeButton = QPushButton('Remove', self)
        self.addTimeButton.clicked.connect(self.addTimeLabel)
        self.removeTimeButton.clicked.connect(self.removeTimeLabel)
        self.timeAxisView.setDragDropMode(QTableView.InternalMove)
        self.timeAxisView.setDragDropOverwriteMode(False)
        self.timeAxisView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.timeAxisView.verticalHeader().hide()
        self.timeAxisModel.rowAppended.connect(self.editTimeLabelName)

        # Concatenation model
        self.timeSeriesDataModel = ConcatenatedModel(self)
        self.timeSeriesDataView = QTableView(self)
        self.timeSeriesDataView.setSelectionMode(QTableView.NoSelection)
        self.timeSeriesDataView.setItemDelegateForColumn(
            1, ComboBoxDelegate(self.timeAxisModel, self.timeSeriesDataView))
        self.timeSeriesDataView.setEditTriggers(QTableView.CurrentChanged
                                                | QTableView.DoubleClicked)
        self.timeSeriesDataView.verticalHeader().hide()
        # Update the label column when some label changes in the label table
        self.timeAxisModel.dataChanged.connect(
            self.timeSeriesDataModel.timeAxisLabelChanged)

        groupTime = QGroupBox(
            title=
            'Add the time points (ordered) and set the correspondence to every selected column',
            parent=self)
        secondRowLayout = QHBoxLayout()
        secondRowLayout.setSpacing(5)
        # labelLayout = QVBoxLayout()
        # lab = QLabel('Here you should define every time point, in the correct order. After adding '
        #              'double-click a row to edit the point name and drag rows to reorder them', self)
        # lab.setWordWrap(True)
        # labelLayout.addWidget(lab)
        # labelLayout.addWidget(self.timeAxisView)
        secondRowLayout.addWidget(self.timeAxisView)
        timeButtonLayout = QVBoxLayout()
        timeButtonLayout.addWidget(self.addTimeButton)
        timeButtonLayout.addWidget(self.removeTimeButton)
        secondRowLayout.addLayout(timeButtonLayout)
        secondRowLayout.addSpacing(30)
        # labelLayout = QVBoxLayout()
        # lab = QLabel('Every selected column for the current series will be listed here. Click the right '
        #              'column of the table to set the time label associated with every original column',
        #              self)
        # lab.setWordWrap(True)
        # labelLayout.addWidget(lab)
        secondRowLayout.addWidget(self.timeSeriesDataView)
        # secondRowLayout.addLayout(labelLayout)
        groupTime.setLayout(secondRowLayout)

        self.outputName = QLineEdit(self)
        self.warningLabel = MessageLabel(text='',
                                         color='orange',
                                         icon=QMessageBox.Warning,
                                         parent=self)
        lastRowLayout = QFormLayout()
        lastRowLayout.addRow('Output variable name:', self.outputName)
        self.outputName.setPlaceholderText('Output name')
        lastRowLayout.setVerticalSpacing(0)
        lastRowLayout.addRow('', self.warningLabel)
        lastRowLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        self.warningLabel.hide()
        self.outputName.textChanged.connect(self.checkOutputName)

        layout = QVBoxLayout(self)
        layout.addWidget(selectionGroup)
        layout.addWidget(groupTime)
        layout.addLayout(lastRowLayout)
        self.checkNoSeries()

    def setWorkbench(self, w: WorkbenchModel) -> None:
        """
        Sets the workbench and initialises every attribute model (one for each frame)
        """
        self.workbench = w
        self.workbenchView.setModel(w)
        # Set a default name for output
        if self.workbench:
            name = 'time_series_{:d}'
            n = 1
            name_n = name.format(n)
            while name_n in self.workbench.names:
                n += 1
                name_n = name.format(n)
            self.outputName.setText(name_n)

    def addSourceFrameModel(self, frameName: str) -> None:
        if self.workbench:
            dfModel = self.workbench.getDataframeModelByName(frameName)
            # Create an attribute model with checkboxes
            standardModel = AttributeTableModel(self,
                                                checkable=True,
                                                editable=False,
                                                showTypes=True)
            standardModel.setFrameModel(dfModel)
            # Create a proxy to filter data in the concatenation
            customProxy = CustomProxyAttributeModel(self)
            customProxy.setSourceModel(standardModel)
            # Add proxy to the list of models
            self.models[frameName] = customProxy
            # Add proxy as source model
            self.timeSeriesDataModel.addSourceModel(customProxy)

    @Slot()
    def checkNoSeries(self) -> None:
        if not self.seriesModel.rowCount():
            self.workbenchView.setEnabled(False)
            self.attributesView.setEnabled(False)
            self.timeAxisView.setEnabled(False)
            self.addTimeButton.setEnabled(False)
            self.removeTimeButton.setEnabled(False)
            self.timeSeriesDataView.setEnabled(False)
        else:
            self.workbenchView.setEnabled(True)
            self.attributesView.setEnabled(True)
            self.timeAxisView.setEnabled(True)
            self.addTimeButton.setEnabled(True)
            self.removeTimeButton.setEnabled(True)
            self.timeSeriesDataView.setEnabled(True)

    def persistOptionsSetForSeries(self, seriesName: str) -> None:
        if seriesName:
            seriesValues: Dict[str,
                               List[Tuple[int,
                                          QPersistentModelIndex]]] = dict()
            for r in range(self.timeSeriesDataModel.rowCount()):
                column0Index: QModelIndex = self.timeSeriesDataModel.index(
                    r, 0, QModelIndex())
                column1Index: QModelIndex = self.timeSeriesDataModel.index(
                    r, 1, QModelIndex())
                sourceIndex: QModelIndex = self.timeSeriesDataModel.mapToSource(
                    column0Index)
                proxy: CustomProxyAttributeModel = sourceIndex.model()
                frameName: str = proxy.sourceModel().frameModel().name
                attrIndexInFrame: int = proxy.mapToSource(sourceIndex).row()
                timeLabelIndex: QPersistentModelIndex = column1Index.data(
                    Qt.DisplayRole)
                if seriesValues.get(frameName, None):
                    seriesValues[frameName].append(
                        (attrIndexInFrame, timeLabelIndex))
                else:
                    seriesValues[frameName] = [(attrIndexInFrame,
                                                timeLabelIndex)]
            self.seriesOptions[seriesName] = seriesValues

    @Slot(str, str)
    def onSeriesSelectionChanged(self, new: str, old: str) -> None:
        # Save current set options
        self.persistOptionsSetForSeries(old)
        if new:
            # Get options of new selection
            newOptions: Dict[str, List[Tuple[int, QPersistentModelIndex]]] = \
                self.seriesOptions.get(new, dict())
            for frameName, proxyModel in self.models.items():
                frameOptions = newOptions.get(frameName, None)
                self.setOptionsForFrame(frameName, frameOptions)
                # Update proxy view on the time label columns
                proxyModel.dataChanged.emit(
                    proxyModel.index(0, 1, QModelIndex()),
                    proxyModel.index(proxyModel.rowCount() - 1, 1,
                                     QModelIndex()),
                    [Qt.DisplayRole, Qt.EditRole])
        # Every time series change clear frame selection in workbench
        self.workbenchView.clearSelection()

    @Slot(str, str)
    def onFrameSelectionChanged(self, newFrame: str, _: str) -> None:
        if not newFrame:
            # Nothing is selected
            return self.attributesView.setAttributeModel(
                AttributeTableModel(self))
        # Check if frame is already in the source models
        if newFrame not in self.models.keys():
            # Create a new proxy and add it to source models
            self.addSourceFrameModel(newFrame)
            if len(self.models) == 1:
                # If it is the first model added then set up the view
                self.timeSeriesDataView.setModel(self.timeSeriesDataModel)
                self.timeSeriesDataView.horizontalHeader(
                ).setSectionResizeMode(0, QHeaderView.Stretch)
                self.timeSeriesDataView.horizontalHeader(
                ).setSectionResizeMode(1, QHeaderView.Stretch)
        # Update the attribute table
        self.attributesView.setAttributeModel(
            self.models[newFrame].sourceModel())

    def setOptionsForFrame(
            self, frameName: str,
            options: Optional[List[Tuple[int,
                                         QPersistentModelIndex]]]) -> None:
        customProxyModel = self.models[frameName]
        attributeTableModel = customProxyModel.sourceModel()
        attributeTableModel.setAllChecked(False)
        if options:
            proxySelection: Dict[int, QPersistentModelIndex] = {
                i: pmi
                for i, pmi in options
            }
            customProxyModel.attributes = proxySelection
            attributeTableModel.setChecked(list(proxySelection.keys()),
                                           value=True)
        else:
            customProxyModel.attributes = dict()

    @Slot()
    def addSeries(self) -> None:
        # Append new row
        self.seriesModel.appendEmptyRow()
        # In oder to avoid copying previous options
        for frameName, proxyModel in self.models.items():
            self.setOptionsForFrame(frameName, None)

    @Slot()
    def removeSeries(self) -> None:
        selected: List[QModelIndex] = self.seriesView.selectedIndexes()
        if selected:
            seriesName: str = selected[0].data(Qt.DisplayRole)
            # Remove row
            self.seriesModel.removeRow(selected[0].row())
            # Remove options for series if they exists
            self.seriesOptions.pop(seriesName, None)

    @Slot()
    def addTimeLabel(self) -> None:
        self.timeAxisModel.appendEmptyRow()

    @Slot()
    def removeTimeLabel(self) -> None:
        selected: List[QModelIndex] = self.timeAxisView.selectedIndexes()
        if selected:
            self.timeAxisModel.removeRow(selected[0].row())
            # Update model
            self.timeSeriesDataModel.dataChanged.emit(
                self.timeSeriesDataModel.index(0, 1, QModelIndex()),
                self.timeSeriesDataModel.index(
                    self.timeSeriesDataModel.rowCount() - 1, 1, QModelIndex()),
                [Qt.DisplayRole, Qt.EditRole])

    @Slot()
    def editSeriesName(self) -> None:
        index = self.seriesModel.index(self.seriesModel.rowCount() - 1, 0,
                                       QModelIndex())
        self.seriesView.setCurrentIndex(index)
        self.seriesView.edit(index)

    @Slot()
    def editTimeLabelName(self) -> None:
        index = self.timeAxisModel.index(self.timeAxisModel.rowCount() - 1, 0,
                                         QModelIndex())
        self.timeAxisView.setCurrentIndex(index)
        self.timeAxisView.edit(index)

    @Slot(str)
    def checkOutputName(self, text: str) -> None:
        if self.workbench and text in self.workbench.names:
            self.warningLabel.setText(
                'Variable {:s} will be overwritten'.format(text))
            self.warningLabel.show()
        else:
            self.warningLabel.hide()
Beispiel #29
0
 def _create_table(self, ) -> QTableView:
     widget = QTableView(self)
     widget.horizontalHeader().hide()
     widget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
     widget.setEditTriggers(QAbstractItemView.AllEditTriggers, )
     return widget
Beispiel #30
0
class Widget(QWidget):
    def __init__(self, data):
        QWidget.__init__(self)

        # Getting the Model
        self.model = CustomTableModel(data)

        # Creating a QTableView
        self.table_view = QTableView()
        self.table_view.setModel(self.model)

        # QTableView Headers
        resize = QHeaderView.ResizeToContents
        self.horizontal_header = self.table_view.horizontalHeader()
        self.vertical_header = self.table_view.verticalHeader()
        self.horizontal_header.setSectionResizeMode(resize)
        self.vertical_header.setSectionResizeMode(resize)
        self.horizontal_header.setStretchLastSection(True)

        # Creating QChart
        self.chart = QtCharts.QChart()
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
        self.add_series("Magnitude (Column 1)", [0, 1])

        # Creating QChartView
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)

        # QWidget Layout
        self.main_layout = QHBoxLayout()
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        # Left layout
        size.setHorizontalStretch(1)
        self.table_view.setSizePolicy(size)
        self.main_layout.addWidget(self.table_view)

        # Right Layout
        size.setHorizontalStretch(4)
        self.chart_view.setSizePolicy(size)
        self.main_layout.addWidget(self.chart_view)

        # Set the layout to the QWidget
        self.setLayout(self.main_layout)

    def add_series(self, name, columns):
        # Create QLineSeries
        self.series = QtCharts.QLineSeries()
        self.series.setName(name)

        # Filling QLineSeries
        for i in range(self.model.rowCount()):
            # Getting the data
            t = self.model.index(i, 0).data()
            date_fmt = "yyyy-MM-dd HH:mm:ss.zzz"

            x = QDateTime().fromString(t, date_fmt).toSecsSinceEpoch()
            y = float(self.model.index(i, 1).data())

            if x > 0 and y > 0:
                self.series.append(x, y)

        self.chart.addSeries(self.series)

        # Setting X-axis
        self.axis_x = QtCharts.QDateTimeAxis()
        self.axis_x.setTickCount(10)
        self.axis_x.setFormat("dd.MM (h:mm)")
        self.axis_x.setTitleText("Date")
        self.chart.addAxis(self.axis_x, Qt.AlignBottom)
        self.series.attachAxis(self.axis_x)
        # Setting Y-axis
        self.axis_y = QtCharts.QValueAxis()
        self.axis_y.setTickCount(10)
        self.axis_y.setLabelFormat("%.2f")
        self.axis_y.setTitleText("Magnitude")
        self.chart.addAxis(self.axis_y, Qt.AlignLeft)
        self.series.attachAxis(self.axis_y)

        # Getting the color from the QChart to use it on the QTableView
        self.model.color = "{}".format(self.series.pen().color().name())
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()

		for i in range(len(self.model.columns)):
			self.table.setColumnWidth(i, self.item_delegate.sizeHint(self.table.viewOptions(), self.model.index(-1, i, QModelIndex())).width())
		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
Beispiel #32
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setWindowTitle("VW Competitive")
        self.setWindowIcon(QIcon(':/images/vw.png'))
        """
        Test wstawienia wartosci do tabeli
        """
        self.table = QTableView()
        self.setCentralWidget(self.table)
        self.sti = QStandardItemModel()
        self.sti.setColumnCount(6)
        self.table.setModel(self.sti)
        self.table.verticalHeader().setDefaultSectionSize(10)
        self.table.horizontalHeader().setDefaultSectionSize(200)
        self.headers = [
            'Year', 'Month', 'Week', 'Sector', 'Category', 'Sub Category',
            'Produkt(4)', 'Branża(I)', 'Kategoria(II)', 'Dział(III)',
            'Producer', 'Brand', 'Sub Brand', 'Film Code', 'Film Code 2',
            'Media', 'Glowne Medium', 'Medium', 'Wydawca Nadawca',
            'Periodyczność', 'Duration', 'Typ reklamy', 'Forma Reklamy',
            'Typ Strony', 'L.emisji', 'Sum.Str', 'Cost', 'PT/OFF', 'TRP',
            'TRP30', 'Channel group', 'Channel type', 'Wyprz', 'Upus', 'Rabat',
            'Wyprze Upust Rabat', 'Model', 'Brand final',
            'Subbrand (brand+Model)', 'Brand Type', 'Segment_detailed',
            'Segment', 'Segment_combined', 'Campaign Type'
        ]
        """
        Forms
        """
        self.excel_form = ExcelForm(self.headers, self)
        self.connect_form = ConnectRaports(self)
        self.filechoser = FileChoser(self)
        self.for_find_duplicate = FindDuplicate(self)
        self.filters_manager = FiltersManager(self)

        self.sti.setHorizontalHeaderLabels(self.headers)
        self.sti.setColumnCount(len(self.headers))
        self.table.setSortingEnabled(True)
        #self.table.horizontalHeader().connect()
        self.connect(self.table.horizontalHeader(),
                     SIGNAL("sectionClicked(int)"), self.showfilterforms)

        self.createActions()
        self.createMenus()
        self.createStatusBar()
        self.readSettings()
        self.set_color_on_header()

    def closeEvent(self, event):
        self.close()

    def open(self):
        self.filechoser.show()
        self.filechoser.clead_data()

    def save(self):
        """
        save data to data base
        :return:
        """
        #deleta rows from data base for compative name
        session = Session()
        comat = session.query(Competitive).filter(
            Competitive.name.ilike(f'%{self.compative_name}%')).first()
        session.query(Data).filter_by(competitive_id=comat.id).delete()

        #read data from row and save to data base
        for row in range(self.sti.rowCount()):
            datas = []
            for col in range(self.sti.columnCount()):
                if col in (0, 1, 2, 20, 24):
                    try:
                        #tutaj poprawic nie chce wpisać
                        if self.sti.item(row, col) is not None:
                            datas.append(int(self.sti.item(row, col).text()))
                        else:
                            datas.append(None)
                    except ValueError:
                        datas.append(None)
                elif col in (25, 26, 28, 29):
                    try:
                        if self.sti.item(row, col) is not None:
                            datas.append(float(self.sti.item(row, col).text()))
                        else:
                            datas.append(None)
                    except ValueError:
                        datas.append(None)
                else:
                    if self.sti.item(row, col) is not None:
                        datas.append(self.sti.item(row, col).text())
                    else:
                        datas.append(None)

            comat.datas.append(Data(*datas))

        session.commit()
        session.close()
        QMessageBox.information(self, "Zapis",
                                "Zapis zakonczyl się powodzeniem.")

    def createActions(self):
        self.openAct = QAction(QIcon(':/images/open.png'),
                               "&Otwórz...",
                               self,
                               shortcut=QKeySequence.Open,
                               statusTip="Otwóż nowe pliki",
                               triggered=self.open)

        self.saveAct = QAction(QIcon(':/images/save.png'),
                               "&Zapisz...",
                               self,
                               shortcut=QKeySequence.Save,
                               statusTip="Zapisz plik",
                               triggered=self.save)

        self.exitAct = QAction("&Zamknij",
                               self,
                               shortcut="Ctrl+Q",
                               statusTip="Zamknij aplikacje",
                               triggered=self.close)

        self.runWordFilter = QAction("Filtry &Automatyczne",
                                     shortcut="Ctrl+A",
                                     statusTip="Urchom filtry automatyczne",
                                     triggered=self.run_filters)

        self.showExcelForm = QAction("Generuj plik excel",
                                     triggered=self.show_excel_form)

        self.ConnectRaports = QAction("Połącz raporty",
                                      triggered=self.show_connect_raports)

        self.FindDuplicate = QAction("Znajdz duplikaty",
                                     triggered=self.show_duplicate_form)

        self.FilterManager = QAction("Filtry Manualne",
                                     triggered=self.show_filter_manager)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&Plik")
        self.fileMenu.addAction(self.openAct)
        self.fileMenu.addAction(self.saveAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)

        self.filterMenu = self.menuBar().addMenu("&Filtry")
        self.filterMenu.addAction(self.runWordFilter)
        self.filterMenu.addAction(self.FilterManager)

        self.excelMenu = self.menuBar().addMenu("&Raporty")
        self.excelMenu.addAction(self.showExcelForm)
        self.excelMenu.addAction(self.ConnectRaports)
        self.excelMenu.addAction(self.FindDuplicate)

    def contextMenuEvent(self, event):
        contextMenu = QMenu(self)
        removeAction = contextMenu.addAction('Usuń')

        action = contextMenu.exec_(self.mapToGlobal(event.pos()))

        if action == removeAction:
            index_list = []
            for model_index in self.table.selectionModel().selectedRows():
                index = QPersistentModelIndex(model_index)
                index_list.append(index)

            for index in index_list:
                self.sti.removeRow(index.row())

    def createStatusBar(self):
        self.statusBar().showMessage("Ready")

    def readSettings(self):
        settings = QSettings("Trolltech", "Application Example")
        pos = settings.value("pos", QPoint(200, 200))
        size = settings.value("size", QSize(800, 800))
        self.resize(size)
        self.move(pos)

    def get_data(self, paths, compative_name):
        """
        receives data from the filechose form
        :param paths: dictionary with paht to techege, adexpert
        :param compative_name: name of raport
        :return:
        """
        self.compative_name = compative_name
        if len(paths[0]) > 0:
            self.techegedata = Excel.get_data(paths[0])
        else:
            self.techegedata = None
        if len(paths[1]) > 0:
            self.adxpert = Excel.get_data(paths[1], False)
        else:
            self.adxpert = None

        #wczytanie arkusza z bazy danych
        session = Session()
        self.compativedata = session.query(Competitive).filter_by(
            name=compative_name).first()

        self.populate_row()
        session.close()

    def populate_row(self):
        """
        read data from compatiedate, techegedata, adxpert and past to rows
        :return:
        """
        # without this section data in column one don't show
        self.sti.setRowCount(0)
        self.sti.setRowCount(1)

        font = QFont()
        font.setPointSize(8)

        #add data from data base
        if self.compativedata:
            for row in self.compativedata.datas:
                rownr = self.sti.rowCount()
                rowvalue = row.values()
                for nr, value in enumerate(rowvalue):
                    item = QStandardItem(f'{value}')
                    item.setFont(font)
                    self.sti.setItem(rownr - 1, nr, item)
                    self.sti.setRowCount(rownr + 1)

        #add data from techegedata
        if self.techegedata:
            for rownr in range(len(self.techegedata[0])):
                self.sti.setRowCount(self.sti.rowCount() + 1)
                for colnr in range(len(self.techegedata)):
                    if len(self.techegedata[colnr]) == 0:
                        continue
                    item = QStandardItem(f'{self.techegedata[colnr][rownr]}')
                    item.setFont(font)
                    self.sti.setItem(self.sti.rowCount() - 2, colnr, item)

        #add data from adexpert
        if self.adxpert:
            for rownr in range(len(self.adxpert[0])):
                self.sti.setRowCount(self.sti.rowCount() + 1)
                for colnr in range(len(self.adxpert)):
                    if len(self.adxpert[colnr]) == 0:
                        continue
                    item = QStandardItem(f'{self.adxpert[colnr][rownr]}')
                    item.setFont(font)
                    self.sti.setItem(self.sti.rowCount() - 2, colnr, item)

        self.sti.removeRow(self.sti.rowCount() - 1)
        self.table.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        QMessageBox.information(self, "Dane", "Dane zostały wczytane")

    def showfilterforms(self, i):
        """
        Show filters for collumn nr"
        :param i:
        :return:
        """
        session = Session()
        filter_ = session.query(FilterF).filter_by(column_nr=i).one_or_none()
        if filter_ is not None and filter_.type == 'manual':
            columns = self.prapercolumns(filter_.columns)
            headersname = [self.headers[i] for i in filter_.columns]
            self.filter = FiltersForm(filter_.id, columns, headersname, self)
            self.filter.show()

        session.close()

    def show_excel_form(self):
        """
        Show excel form
        :return:
        """
        self.excel_form.set_compatives()
        self.excel_form.show()

    def show_connect_raports(self):
        """
        Show  connect rapot
        :return:
        """
        self.connect_form.set_raports()
        self.connect_form.show()

    def show_duplicate_form(self):
        """
        show duplicate form
        """
        self.for_find_duplicate.set_raports()
        self.for_find_duplicate.show()

    def show_filter_manager(self):
        """
        show filter manager form
        """
        self.filters_manager.show()

    def prapercolumns(self, columns):
        """
        get unic data from sending columns
        :param args:
        :return:
        """
        mainlist = []
        for col in columns:
            collist = []
            for row in range(self.sti.rowCount()):
                if self.sti.item(row, col) is not None:
                    collist.append(self.sti.item(row, col).text())
            mainlist.append(collist)

        return list(set(zip(*mainlist)))

    def replace_column(self, col_nr, assignded_column):
        """
        replace column with new data
        :param col_nr:
        :param assignded_column:
        :return:
        """
        self.sti.takeColumn(col_nr)
        self.sti.insertColumn(col_nr, assignded_column)
        self.sti.setHorizontalHeaderLabels(self.headers)
        self.set_color_on_header()

    """
    
    Filters
    
    """

    def assign_value_for_filter(self, filter_id, show=True):
        """
        preper list with value from main filter, send it to make_filter_list.
        Replace column for filter_id with column with assigned data
        :param filter_id:
        :return:
        """
        session = Session()
        filter_ = session.query(FilterF).get(filter_id)
        rows = []
        for row in range(self.sti.rowCount()):
            row_value = [
                self.sti.item(row, col).text() for col in filter_.columns
            ]
            rows.append(row_value)

        read_rows = self.make_filter_list(filter_id, rows)
        col_nr = filter_.column_nr
        self.sti.takeColumn(col_nr)
        self.sti.insertColumn(col_nr, read_rows)
        self.sti.setHorizontalHeaderLabels(self.headers)
        session.close()
        self.set_color_on_header()

        if show:
            QMessageBox.information(self, "Informacja", "Operacja zakończona.")

    @staticmethod
    def make_filter_list(filter_id, rows):
        """
        make list with assigned value
        :param filter_id:
        :param rows:
        :return:
        """
        session = Session()
        filter_ = session.query(FilterF).get(filter_id)

        ready_valus = []
        for row in rows:
            flag = False
            row = [i.strip().lower() for i in row]
            for category in filter_.categorys:
                items = [[b.strip().lower() for b in a]
                         for a in category.items]
                if row in items:
                    #make QStandardItem to make column in sti model
                    item = QStandardItem(str(category.name))
                    ready_valus.append(item)
                    flag = True
            if flag is False:
                item = QStandardItem('')
                ready_valus.append(item)

        session.close()
        return ready_valus

    """
    filters: words, cut
    """

    def run_filters(self):
        """
        make filters
        :return:
        """
        session = Session()
        # filters_ = session.query(FilterF).filter_by(type='words').all()
        filters_ = session.query(FilterF).all()
        for fil in filters_:

            if fil.type == 'words':
                rows = self.get_data_from_columns(fil.columns)
                assignded_column = self.make_words_list(fil.id, rows)
                self.replace_column(fil.column_nr, assignded_column)

            elif fil.type == 'cut':
                if fil.name == 'model':
                    rows = self.get_data_from_columns(fil.columns)
                    assignded_column = self.filter_cut_model(rows)
                    self.replace_column(fil.column_nr, assignded_column)

                elif fil.name == 'subbrand_brand_model':
                    rows = self.get_data_from_columns(fil.columns)
                    assignded_column = self.join_columns(rows)
                    self.replace_column(fil.column_nr, assignded_column)

        session.close()
        QMessageBox.information(self, "Informacja", "Operacja zakończona.")

    def get_data_from_columns(self, columns_nr):
        """
        get data for sending columns
        :param columns_nr:
        :return: return list of value from table
        """
        rows = []
        for row in range(self.sti.rowCount()):
            row_value = []
            for col in columns_nr:
                if self.sti.item(row, col) is not None:
                    row_value.append(self.sti.item(row, col).text())
                else:
                    row_value.append('')
            # row_value = [self.sti.item(row, col).text() for col in columns_nr]
            rows.append(row_value)
        return rows

    @staticmethod
    def make_words_list(filter_id, rows):
        """
        make words list for filters,
        if find word in list assigned name of category
        :param filter_id:
        :param rows:
        :return:
        """

        session = Session()
        filter_ = session.query(FilterF).get(filter_id)

        ready_valus = []
        for row in rows:
            flag = False
            row = [i.lower() for i in row]
            row = ' '.join(row)
            for category in filter_.categorys:
                words = [b.lower() for b in category.words]
                for word in words:
                    if word in row:
                        item = QStandardItem(str(category.name))
                        ready_valus.append(item)
                        flag = True
                        break
            if flag is False:
                item = QStandardItem('')
                ready_valus.append(item)

        session.close()
        return ready_valus

    def filter_cut_model(self, rows):
        """
        cut ferst word from string
        :param rows:
        :return:
        """
        ready_values = []
        for row in rows:
            item = QStandardItem((row[1].replace(row[0], '')).strip())
            ready_values.append(item)

        return ready_values

    def join_columns(self, rows):
        """
        join column in list rows
        """
        temp = [QStandardItem(' '.join(x)) for x in rows]
        return temp

    def set_color_on_header(self):
        """
        changes the color of the header
        :return:
        """

        session = Session()
        filtersf = session.query(FilterF).all()

        for filterf in filtersf:
            if filterf.type == 'manual':
                self.table.model().setHeaderData(filterf.column_nr,
                                                 Qt.Horizontal,
                                                 QBrush(QColor(121, 166, 210)),
                                                 Qt.BackgroundRole)
                self.table.model().setHeaderData(
                    filterf.column_nr, Qt.Horizontal,
                    self.headers[filterf.column_nr], Qt.DisplayRole)
            if filterf.type in ('words', 'cut'):
                self.table.model().setHeaderData(filterf.column_nr,
                                                 Qt.Horizontal,
                                                 QBrush(QColor(212, 214, 219)),
                                                 Qt.BackgroundRole)
                self.table.model().setHeaderData(
                    filterf.column_nr, Qt.Horizontal,
                    self.headers[filterf.column_nr], Qt.DisplayRole)
        session.close()
Beispiel #33
0
class AutoFilterWidget(QWidget):
    """A widget to show the auto filter 'menu'."""
    def __init__(self, parent):
        """Initialize class."""
        super().__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self.model = MinimalTableModel(self)
        self.model.flags = self.model_flags
        self.view = QTableView(self)
        self.view.setModel(self.model)
        self.view.verticalHeader().hide()
        self.view.horizontalHeader().hide()
        self.view.setShowGrid(False)
        check_box_delegate = CheckBoxDelegate(self)
        self.view.setItemDelegateForColumn(0, check_box_delegate)
        check_box_delegate.data_committed.connect(
            self._handle_check_box_data_committed)
        self.button = QPushButton("Ok", self)
        self.button.setFlat(True)
        layout.addWidget(self.view)
        layout.addWidget(self.button)
        self.button.clicked.connect(self.hide)
        self.hide()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

    def model_flags(self, index):
        """Return index flags."""
        if not index.isValid():
            return Qt.NoItemFlags
        if index.column() == 1:
            return ~Qt.ItemIsEditable
        return Qt.ItemIsEditable

    @Slot("QModelIndex", name="_handle_check_box_data_committed")
    def _handle_check_box_data_committed(self, index):
        """Called when checkbox delegate wants to edit data. Toggle the index's value."""
        data = index.data(Qt.EditRole)
        model_data = self.model._main_data
        row_count = self.model.rowCount()
        if index.row() == 0:
            # Ok row
            value = data in (None, False)
            for row in range(row_count):
                model_data[row][0] = value
            self.model.dataChanged.emit(self.model.index(0, 0),
                                        self.model.index(row_count - 1, 0))
        else:
            # Data row
            self.model.setData(index, not data)
            self.set_ok_index_data()

    def set_ok_index_data(self):
        """Set data for ok index based on data from all other indexes."""
        ok_index = self.model.index(0, 0)
        true_count = 0
        for row_data in self.model._main_data[1:]:
            if row_data[0] == True:
                true_count += 1
        if true_count == len(self.model._main_data) - 1:
            self.model.setData(ok_index, True)
        elif true_count == 0:
            self.model.setData(ok_index, False)
        else:
            self.model.setData(ok_index, None)

    def set_values(self, values):
        """Set values to show in the 'menu'. Reset model using those values and update geometry."""
        self.model.reset_model([[None, "All"]] + values)
        self.set_ok_index_data()
        self.view.horizontalHeader().hideSection(
            2)  # Column 2 holds internal data (cls_id_set)
        self.view.resizeColumnsToContents()
        width = self.view.horizontalHeader().length() + qApp.style(
        ).pixelMetric(QStyle.PM_ScrollBarExtent)
        self.setFixedWidth(width + 2)
        height = self.view.verticalHeader().length() + self.button.height()
        parent_height = self.parent().height()
        self.setFixedHeight(min(height, parent_height / 2) + 2)

    def set_section_height(self, height):
        """Set vertical header default section size as well as button height."""
        self.view.verticalHeader().setDefaultSectionSize(height)
        self.button.setFixedHeight(height)