Esempio n. 1
0
    def update_library(self):
        self.library = get_library()

        self.library_table.clear()
        self.library_table.setStyleSheet(
            "selection-background-color: blue")  # 设置选中背景色
        self.library_table.setRowCount(len(self.library['books']))
        self.library_table.setColumnCount(5)  # TODO: 改掉硬编码??
        self.library_table.setHorizontalHeaderLabels(
            ['Title', 'Authors', 'Tags', 'Date', 'Size(MB)'])

        self.library_table.setAlternatingRowColors(True)
        self.library_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.library_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.library_table.setSelectionMode(QTableWidget.SingleSelection)

        self.model = QtGui.QStandardItemModel(self)
        for i, book in enumerate(self.library['books']):
            for j, cell in enumerate(
                (book['title'], book['author'], book['tags'], book['date'],
                 book['size'])):
                item = QTableWidgetItem(cell)
                item.setTextAlignment(Qt.AlignCenter)
                self.library_table.setItem(i, j, item)

        self.library_table.resizeColumnsToContents()
Esempio n. 2
0
    def writeModeData(self, data):
        ''' get data output and add on QtableWidgets '''
        packetsIp = data.split(':[creds]')[1].split('HTTP username:'******'username:'******'Username'].append(username.split('=')[1])
            if 'password:'******'Password'].append(password.split('=')[1])

        Headers = []
        if packetsIp not in self.THeaders[
                'Source/Destination'] and not 'SessionID' in packetsIp:
            self.THeaders['Source/Destination'].append(packetsIp)
        self.setRowCount(len(self.THeaders['Username']))
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                item = QTableWidgetItem(item)
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.setItem(m, n, item)
        self.setHorizontalHeaderLabels(self.THeaders.keys())
        self.verticalHeader().setDefaultSectionSize(27)
        self.scrollToBottom()
Esempio n. 3
0
    def reload_harmonics_table(self):
        horHeaders = []
        verHeaders = []

        self.table.itemChanged.disconnect(self.table_item_changed)

        self.table.clear()

        row_count = self.table.rowCount()

        for n in range(0, row_count):
            self.table.removeRow(0)

        for index in range(0, self.harmonic_maximum_index + 1):
            self.table.insertRow(0)

        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)

            for m, item in enumerate(self.data[key]):
                table_item = QTableWidgetItem(str(item))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(m, n, table_item)
                verHeaders.append(str(m))

        self.table.setHorizontalHeaderLabels(horHeaders)
        self.table.setVerticalHeaderLabels(verHeaders)

        self.table.resizeRowsToContents()

        for i in range(0, 3):
            self.table.setColumnWidth(i, 70)

        self.table.itemChanged.connect(self.table_item_changed)
Esempio n. 4
0
    def restoreWidgetPosition(self):
        super().restoreWidgetPosition()

        self.table = QTableWidget(self.harmonic_maximum_index + 1, 3)
        self.table.setAlternatingRowColors(True)
        self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed)

        for i in range(0, 3):
            self.table.setColumnWidth(i, 70)

        horHeaders = []
        verHeaders = []

        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)

            for m, item in enumerate(self.data[key]):
                table_item = QTableWidgetItem(str(item))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(m, n, table_item)
                verHeaders.append(str(m))

        self.table.setHorizontalHeaderLabels(horHeaders)
        self.table.setVerticalHeaderLabels(verHeaders)
        self.table.resizeRowsToContents()

        self.table.itemChanged.connect(self.table_item_changed)

        self.scrollarea.setWidget(self.table)
        self.scrollarea.setWidgetResizable(1)

        gui.rubber(self.controlArea)
Esempio n. 5
0
    def showDescriptors(self, processMIdx):
        try:
            self.handlesTable.setRowCount(0)
            self.handlesTable.clearContents()
            descriptors = self.model.getProcDescriptors(processMIdx)
            libs = self.model.getProcLibraries(processMIdx)
            self.handlesTable.setRowCount(len(descriptors) + len(libs))
        except PermissionError:
            self.handlesTable.setRowCount(1)
            self.handlesTable.setSpan(0, 0, 1, 2)
            permDeniedMsg = QTableWidgetItem('<Permission Denied>')
            permDeniedMsg.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            permDeniedMsg.setTextAlignment(Qt.AlignCenter)
            permDeniedMsg.setTextColor(QColor(255, 0, 0))
            self.handlesTable.setItem(0, 0, permDeniedMsg)
        else:
            for row, descriptor in enumerate(descriptors):
                typeItem = QTableWidgetItem(descriptor.type)
                typeItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                nameItem = QTableWidgetItem(descriptor.name)
                nameItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.handlesTable.setItem(row, 0, typeItem)
                self.handlesTable.setItem(row, 1, nameItem)

            for row, libName in enumerate(libs, start=len(descriptors)):
                typeItem = QTableWidgetItem('Shared Library')
                typeItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                nameItem = QTableWidgetItem(libName)
                nameItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.handlesTable.setItem(row, 0, typeItem)
                self.handlesTable.setItem(row, 1, nameItem)
Esempio n. 6
0
    def load_config_value(self):
        # checks
        self.check_answer_timeout.setChecked(
            UserConfig.SHOW_ANSWER_ON_CARD_TIMEOUT)
        self.check_overall.setChecked(UserConfig.SHOW_OVERALL_STATISTICS)
        self.check_deck.setChecked(UserConfig.SHOW_DECK_STATISTICS)

        self.check_start.setChecked(UserConfig.PLAY_SOUNDS['start'])
        self.check_break.setChecked(UserConfig.PLAY_SOUNDS['break'])
        self.check_almost_timeout.setChecked(
            UserConfig.PLAY_SOUNDS['half_way_limit'])
        self.check_timeout.setChecked(UserConfig.PLAY_SOUNDS['timeout'])
        self.check_abort.setChecked(UserConfig.PLAY_SOUNDS['abort'])

        # value
        self.spin_card_secs.setValue(UserConfig.ANSWER_TIMEOUT_SECONDS)

        # minutes
        break_min_dicts = UserConfig.BREAK_MINUTES
        sorted_keys = sorted(break_min_dicts.keys())[:7]
        minites_ints = [int(re.findall("\d+", s)[0]) for s in sorted_keys]

        for c in range(UserConfig.BREAK_MINUTES.items()[0].__len__()):
            for r in range(sorted_keys.__len__()):
                if c:
                    item = QTableWidgetItem(
                        str(break_min_dicts[sorted_keys[r]]))
                else:
                    item = QTableWidgetItem(str(minites_ints[r]))
                item.setTextAlignment(Qt.AlignCenter)
                self.tableWidget.setItem(r, c, item)
Esempio n. 7
0
 def setGlobalRow(self,row,columns):
     for column,cell in enumerate(columns):
         widget = QTableWidgetItem(str(cell))
         if column > 0:
             widget.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
         self.projectSummary.setItem(row,column,widget)
     self.updateTotals()
Esempio n. 8
0
    def generateIdField(id=''):
        """
		@rtype: QTableWidgetItem
		"""
        idField = QTableWidgetItem(str(id))
        idField.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        idField.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        return idField
Esempio n. 9
0
 def _get_table_widget_item_centered(self, text):
     """
     return a TableWidgetItem with the text supplied and centered vertical and  horizontally
     :param text: text of the item
     :return:
     """
     item = QTableWidgetItem(unicode(text))
     item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     return item
Esempio n. 10
0
	def generateIdField(id=''):
		"""
		@rtype: QTableWidgetItem
		"""
		idField = QTableWidgetItem(str(id))
		idField.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
		idField.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

		return idField
Esempio n. 11
0
 def initTable(self, mlist):
     self.tableWidget.setRowCount(len(mlist))
     for (i, v) in enumerate(mlist):
         for (j, item) in enumerate(v):
             if type(item) != str:
                 item = unicode(item)
             if item == None:
                 item = u""
             tabItem = QTableWidgetItem(item)
             tabItem.setTextAlignment(Qt.AlignCenter)
             self.tableWidget.setItem(i, j, tabItem)
Esempio n. 12
0
    def add_log_row(self, log_content_array):
        # add row to the QTableWidget for logs
        row_count = self.logs_ui.logs_table.rowCount()
        self.logs_ui.logs_table.setRowCount(row_count + 1)
        event_sign_image_path = None
        # log levels:
        # debug
        # info
        # notice
        # warning
        # error
        if log_content_array["log_event_type"] == "info":
            info_png_path = os.path.join(os.path.dirname(__file__),
                                         'resources/img/info.png')
            event_sign_image_path = str(info_png_path)
        elif log_content_array["log_event_type"] == "warning":
            warning_png_path = os.path.join(os.path.dirname(__file__),
                                            'resources/img/warning.png')
            event_sign_image_path = str(warning_png_path)
        elif log_content_array["log_event_type"] == "notice":
            notice_png_path = os.path.join(os.path.dirname(__file__),
                                           'resources/img/notice.png')
            event_sign_image_path = str(notice_png_path)
        elif log_content_array["log_event_type"] == "debug":
            debug_png_path = os.path.join(os.path.dirname(__file__),
                                          'resources/img/debug.png')
            event_sign_image_path = str(debug_png_path)
        elif log_content_array["log_event_type"] == "success":
            debug_png_path = os.path.join(os.path.dirname(__file__),
                                          'resources/img/success.png')
            event_sign_image_path = str(debug_png_path)
        elif log_content_array["log_event_type"] == "error":
            error_png_path = os.path.join(os.path.dirname(__file__),
                                          'resources/img/error.png')
            event_sign_image_path = str(error_png_path)

        image = ImageWidget(event_sign_image_path, self)
        widget = QWidget()
        hbl = QHBoxLayout()
        hbl.setMargin(0)
        hbl.setSpacing(0)
        hbl.addWidget(image)
        widget.setLayout(hbl)
        self.logs_ui.logs_table.setCellWidget(row_count, 0, widget)
        self.logs_ui.logs_table.setItem(
            row_count, 1,
            QTableWidgetItem(log_content_array["log_event_type"]))
        titleitem = QTableWidgetItem(log_content_array["title"])
        titleitem.setTextAlignment(QtCore.Qt.AlignCenter)
        self.logs_ui.logs_table.setItem(row_count, 2, titleitem)
        self.logs_ui.logs_table.setItem(
            row_count, 3, QTableWidgetItem(log_content_array["description"]))

        return 1
Esempio n. 13
0
 def updateTotals(self):
     for col in range(0,4):
         colTot = 0
         for row in range(0,5):
             if self.projectSummary.item(row,col):
                 colTot += float(self.projectSummary.item(row,col).text())
         widget = QTableWidgetItem(str(colTot))
         if col > 0:
             widget.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
         self.projectSummary.setItem(5,col,widget)
     self.globalSummaryToCSV()
Esempio n. 14
0
    def fillHeader(self, row, chain):
        item = chain.createTableWidgetItem()
        self.table.setSpan(row, 0, 1, 3)
        self.table.setItem(row, 0, item)

        item = QTableWidgetItem()
        unsetFlag(item, Qt.ItemIsEditable)
        item.setText(tr("Translated to"))
        item.setTextAlignment(Qt.AlignHCenter)
        item.setBackgroundColor(DECISION_COLORS['ACCEPT'])
        self.table.setSpan(row, 4, 1, 3)
        self.table.setItem(row, 4, item)
Esempio n. 15
0
    def add_log_row(self, log_content_array):
        # add row to the QTableWidget for logs
        row_count = self.logs_ui.logs_table.rowCount()
        self.logs_ui.logs_table.setRowCount(row_count + 1)
        event_sign_image_path = None

        if log_content_array['log_event_type'] == 'info':
            info_png_path = os.path.join(os.path.dirname(__file__),
                                         'resources/img/info.png')
            event_sign_image_path = str(info_png_path)
        elif log_content_array['log_event_type'] == 'warning':
            warning_png_path = os.path.join(os.path.dirname(__file__),
                                            'resources/img/warning.png')
            event_sign_image_path = str(warning_png_path)
        elif log_content_array['log_event_type'] == 'notice':
            notice_png_path = os.path.join(os.path.dirname(__file__),
                                           'resources/img/notice.png')
            event_sign_image_path = str(notice_png_path)
        elif log_content_array['log_event_type'] == 'debug':
            debug_png_path = os.path.join(os.path.dirname(__file__),
                                          'resources/img/debug.png')
            event_sign_image_path = str(debug_png_path)
        elif log_content_array['log_event_type'] == 'success':
            debug_png_path = os.path.join(os.path.dirname(__file__),
                                          'resources/img/success.png')
            event_sign_image_path = str(debug_png_path)
        elif log_content_array['log_event_type'] == 'error':
            error_png_path = os.path.join(os.path.dirname(__file__),
                                          'resources/img/error.png')
            event_sign_image_path = str(error_png_path)

        image = ImageWidget(event_sign_image_path, self)
        widget = QWidget()
        hbl = QHBoxLayout()
        hbl.setMargin(0)
        hbl.setSpacing(0)
        hbl.addWidget(image)
        widget.setLayout(hbl)

        self.logs_ui.logs_table.setCellWidget(row_count, 0, widget)
        self.logs_ui.logs_table.setItem(
            row_count, 1,
            QTableWidgetItem(log_content_array['log_event_type']))

        titleitem = QTableWidgetItem(log_content_array['title'])
        titleitem.setTextAlignment(QtCore.Qt.AlignCenter)

        self.logs_ui.logs_table.setItem(row_count, 2, titleitem)
        self.logs_ui.logs_table.setItem(
            row_count, 3, QTableWidgetItem(log_content_array['description']))

        return 1
    def search_profiles(self):
        try:
            self.table.itemClicked.disconnect(self.table_item_clicked)
            self.table.clear()

            row_count = self.table.rowCount()
            for n in range(0, row_count):
                self.table.removeRow(0)

            self.table.setHorizontalHeaderLabels(self.horHeaders)

            profiles = dabam.dabam_summary_dictionary(surface=self.get_dabam_shape(),
                                                      slp_err_from=self.slope_error_from*1e-6,
                                                      slp_err_to=self.slope_error_to*1e-6,
                                                      length_from=self.dimension_y_from / self.si_to_user_units,
                                                      length_to=self.dimension_y_to / self.si_to_user_units)

            for index in range(0, len(profiles)):
                self.table.insertRow(0)

            for index in range(0, len(profiles)):
                table_item = QTableWidgetItem(str(profiles[index]["entry"]))
                table_item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(index, 0, table_item)
                table_item = QTableWidgetItem(str(profiles[index]["surface"]))
                table_item.setTextAlignment(Qt.AlignLeft)
                self.table.setItem(index, 1, table_item)
                table_item = QTableWidgetItem(str(numpy.round(profiles[index]["length"]*self.si_to_user_units, 3)))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(index, 2, table_item)
                table_item = QTableWidgetItem(str(numpy.round(profiles[index]["hgt_err"]*1e9, 3)))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(index, 3, table_item)
                table_item = QTableWidgetItem(str(numpy.round(profiles[index]["slp_err"]*1e6, 3)))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(index, 4, table_item)

            self.table.setHorizontalHeaderLabels(self.horHeaders)
            self.table.resizeRowsToContents()
            self.table.setSelectionBehavior(QAbstractItemView.SelectRows)

            self.table.itemClicked.connect(self.table_item_clicked)

            self.overlay_search.hide()

        except Exception as exception:
            self.overlay_search.hide()

            QMessageBox.critical(self, "Error",
                                 exception.args[0],
                                 QMessageBox.Ok)
Esempio n. 17
0
    def setmydata(self, data):
        self.setRowCount(len(data[data.keys()[0]]))

        for n, key in enumerate(data.keys()):
            for m, item in enumerate(data[key]):
                newitem = QTableWidgetItem(item)
                newitem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.setItem(m, n, newitem)

        for m in data['Energy']:
            if m == ('-'):
                self.status.append(None)
            else:
                self.status.append('Inactive')
    def add_item(self, row, col, text, centre=False):
        """
        Add a textual item to the table widget.

        Params::
        row -- row
        col -- col
        text -- text
        """
        item = QTableWidgetItem(str(text))

        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        self.setItem(row, col, item)
Esempio n. 19
0
    def set_data(self, phases, values, import_phases, import_values):

        self.phases = phases
        self.values = values
        self.import_phases = import_phases
        self.import_values = import_values

        self.table.setRowCount(len(self.phases))

        for (index, phase) in enumerate(self.phases):
            phase_item = QTableWidgetItem('%.12f' % phase)
            phase_item.setTextAlignment(Qt.AlignRight)

            value_item = QTableWidgetItem('%.12f' % self.values[index])
            value_item.setTextAlignment(Qt.AlignRight)
            self.table.setItem(index, 0, phase_item)
            self.table.setItem(index, 1, value_item)

            if phase in import_phases :
                import_index = import_phases.index(phase)

                value_item = QTableWidgetItem('%.12f' % import_values[import_index])
                value_item.setTextAlignment(Qt.AlignRight)

                delta_flux_item = QTableWidgetItem('%.12f' % (import_values[import_index] - self.values[index]))
                delta_flux_item.setTextAlignment(Qt.AlignRight)

                self.table.setItem(index, 2, value_item)
                self.table.setItem(index, 3, delta_flux_item)
    def add_item(self, row, col, text, centre=False):
        """
        Add a textual item to the table widget.

        Params::
        row -- row
        col -- col
        text -- text
        """
        item = QTableWidgetItem(str(text))
        if centre:
            item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        #item.setStyleSheet("{ margin-bottom: 10; }")
        self.tableWidget.setItem(row, col, item)
Esempio n. 21
0
    def extend_rows(self):

        nb_rows = self.rowCount()
        self.setRowCount(nb_rows + 1)
        # self.setSpan(nb_rows, 0, 1, 1)
        mtt_ttc = QTableWidgetItem(u"TOTAUX: ")
        mtt_ttc.setTextAlignment(Qt.AlignRight)
        self.setItem(nb_rows, 0, mtt_ttc)

        ttl_remainig = 0
        tall_in = 0
        tall_out = 0

        for row_num in xrange(0, self.data.__len__()):
            all_in = is_int(unicode(self.item(row_num, 1).text()))
            tall_in += all_in
            all_out = is_int(unicode(self.item(row_num, 2).text()))
            tall_out += all_out
            remaining = is_int(unicode(self.item(row_num, 3).text()))
            ttl_remainig += remaining

        # Montant TTC
        tall_in = QTableWidgetItem(formatted_number(tall_in))
        tall_in.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 1, 1, tall_in)
        tall_out = QTableWidgetItem(formatted_number(tall_out))
        tall_out.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 1, 2, tall_out)

        ttl_remainig = QTableWidgetItem(formatted_number(ttl_remainig))
        ttl_remainig.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 1, 3, ttl_remainig)
Esempio n. 22
0
    def showResult(self):
        for i in xrange(self.programLogic.inputCount()):
            itemInputNumber = QTableWidgetItem()
            itemInputNumber.setText(str(i + 1))
            itemInputNumber.setTextAlignment(Qt.AlignCenter)
            itemInputNumber.setFlags(Qt.ItemIsEnabled)
            self.uiDataBefore.setItem(0, i, itemInputNumber)

            itemOriginalInputs = QTableWidgetItem()
            originalInput = self.programLogic.currentInputs()[i]
            itemOriginalInputs.setText(self.formatNumber(originalInput))
            itemOriginalInputs.setTextAlignment(Qt.AlignCenter)
            itemOriginalInputs.setFlags(Qt.ItemIsEnabled)
            self.uiDataBefore.setItem(1, i, itemOriginalInputs)

            itemNormalizedInputs = QTableWidgetItem()
            itemNormalizedInputs.setText(self.formatNumber(self.programLogic.currentNormalizedInputs()[i]))
            itemNormalizedInputs.setTextAlignment(Qt.AlignCenter)
            itemNormalizedInputs.setFlags(Qt.ItemIsEnabled)
            self.uiDataBefore.setItem(2, i, itemNormalizedInputs)

            itemWeights = QTableWidgetItem()
            itemWeights.setText(self.formatNumber(self.programLogic.currentPrevWeights()[i]))
            itemWeights.setTextAlignment(Qt.AlignCenter)
            itemWeights.setFlags(Qt.ItemIsEnabled)
            self.uiDataBefore.setItem(3, i, itemWeights)

        self.uiLabelComment.setText('Comment: ' + self.programLogic.currentComment())
        self.uiCorrectBefore.setText(str(self.programLogic.currentExpectedOutput()))
Esempio n. 23
0
    def changed_value(self, refresh=False):
        """ Calcule les Resultat """
        mtt_ht = 0
        for row_num in xrange(0, self.data.__len__()):
            last_report = Product.filter(name=str(self.item(row_num, 1)
                                         .text())).get().last_report
            try:
                qtremaining = last_report.remaining
            except AttributeError:
                qtremaining = 0

            qtsaisi = is_int(self.cellWidget(row_num, 0).text())
            pu = is_int(self.cellWidget(row_num, 2).text())

            self.isvalid = True
            viderreur_qtsaisi = ""
            viderreur_pu = ""
            stylerreur = "background-color: rgb(255, 235, 235);" + \
                         "border: 3px double SeaGreen"
            if qtsaisi == 0:
                viderreur_qtsaisi = stylerreur
                self.cellWidget(row_num, 0).setToolTip(u"obligatoire")
                self.isvalid = False
            if pu == 0:
                viderreur_pu = stylerreur
                self.cellWidget(row_num, 0).setToolTip(u"obligatoire")
                self.isvalid = False

            self.cellWidget(row_num, 0).setStyleSheet(viderreur_qtsaisi)
            self.cellWidget(row_num, 2).setStyleSheet(viderreur_pu)

            self.cellWidget(row_num, 0).setToolTip("")
            if qtremaining < qtsaisi:
                self.cellWidget(row_num, 0).setStyleSheet("font-size:20px;"
                                                          " color: red")
                self.cellWidget(row_num,
                                0).setToolTip(u"%s est > %s (stock"
                                              u" remaining)" % (qtsaisi,  qtremaining))
                # self.isvalid = False
                # return False

            ui_item = (qtsaisi * pu)
            mtt_ht += ui_item
            montt = QTableWidgetItem(formatted_number(ui_item))
            montt.setTextAlignment(Qt.AlignRight)
            self.setItem(row_num, 3, montt)
        monttc = QTableWidgetItem(formatted_number(mtt_ht))
        monttc.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 1, 3, monttc)
Esempio n. 24
0
    def changed_value(self, refresh=False):

        some = 0
        for row_num in xrange(0, self.data.__len__()):
            ui_item = (is_int(self.item(row_num, 1).text()) *
                       is_int(self.cellWidget(row_num, 2).text()))
            some += ui_item
            ui_item_ = QTableWidgetItem(formatted_number(ui_item))
            ui_item_.setTextAlignment(Qt.AlignRight)
            self.setItem(row_num, 3, ui_item_)
        row_num += 1
        som_val = QTableWidgetItem(formatted_number(some))
        som_val.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 1, 2, QTableWidgetItem(u"%s" % u"TOTAUX"))
        self.setItem(row_num + 1, 3, som_val)
Esempio n. 25
0
    def changed_value(self, refresh=False):

        some = 0
        for row_num in xrange(0, self.data.__len__()):
            ui_item = (is_int(self.item(row_num, 1).text()) *
                       is_int(self.cellWidget(row_num, 2).text()))
            some += ui_item
            ui_item_ = QTableWidgetItem(formatted_number(ui_item))
            ui_item_.setTextAlignment(Qt.AlignRight)
            self.setItem(row_num, 3, ui_item_)
        row_num += 1
        som_val = QTableWidgetItem(formatted_number(some))
        som_val.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 1, 2, QTableWidgetItem(u"%s" % u"TOTAUX"))
        self.setItem(row_num + 1, 3, som_val)
Esempio n. 26
0
 def addDefPol(self):
     qtext, ok = QInputDialog.getText(self, 'Value', 'Field Name:')
     text = str(qtext)
     if ok:
         self.config.defpol_index.append(text)
         self.config.defpol[text] = 'T'
         lastRow = self.g_defpol.rowCount()
         self.g_defpol.insertRow(lastRow)
         it = QTableWidgetItem(text)
         it1 = QTableWidgetItem('T')
         it1.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
         self.g_defpol.blockSignals(True)
         self.g_defpol.setItem(lastRow, 0, it)
         self.g_defpol.setItem(lastRow, 1, it1)
         self.g_defpol.blockSignals(False)
Esempio n. 27
0
 def slot_reset_register_ui(self, regbank_name, sheet_name):
     if (self.register._regbank_name==regbank_name and
             self.register._module_instance_name==sheet_name):
         self.lineEdit_registerValue.blockSignals(True)
         self.lineEdit_registerValue.setText("")
         self.lineEdit_registerValue.blockSignals(False)
         row_idx = 0
         self.tableWidget_subfieldsView.blockSignals(True)
         for subfield_name in self.register._subfields_db.keys():
             view_field = self.view_fields[2]
             text = "--"
             item = QTableWidgetItem(text); item.setTextAlignment(Qt.AlignCenter)
             self.tableWidget_subfieldsView.setItem(row_idx, view_field.col_num, item)
             row_idx += 1
         self.tableWidget_subfieldsView.blockSignals(False)
         self.slot_update_register_ui()
Esempio n. 28
0
 def writeModeData(self, data):
     ''' get data output and add on QtableWidgets '''
     self.THeaders['Plugin'].append(data.keys()[0])
     self.THeaders['Logging'].append(data[data.keys()[0]])
     Headers = []
     self.setRowCount(len(self.THeaders['Plugin']))
     for n, key in enumerate(self.THeaders.keys()):
         Headers.append(key)
         for m, item in enumerate(self.THeaders[key]):
             item = QTableWidgetItem(item)
             if key != 'Logging':
                 item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
             self.setItem(m, n, item)
     self.setHorizontalHeaderLabels(list(self.THeaders.keys()))
     self.verticalHeader().setDefaultSectionSize(27)
     self.scrollToBottom()
Esempio n. 29
0
 def writeModeData(self,data):
     ''' get data output and add on QtableWidgets '''
     self.THeaders['Plugin'].append(data.keys()[0])
     self.THeaders['Logging'].append(data[data.keys()[0]])
     Headers = []
     self.setRowCount(len(self.THeaders['Plugin']))
     for n, key in enumerate(self.THeaders.keys()):
         Headers.append(key)
         for m, item in enumerate(self.THeaders[key]):
             item = QTableWidgetItem(item)
             if key != 'Logging':
                 item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
             self.setItem(m, n, item)
     self.setHorizontalHeaderLabels(self.THeaders.keys())
     self.verticalHeader().setDefaultSectionSize(27)
     self.scrollToBottom()
Esempio n. 30
0
 def writeModeData(self,data):
     ''' get data output and add on QtableWidgets '''
     self.THeaders['Username'].append(data['POSTCreds']['User'])
     self.THeaders['Password'].append(data['POSTCreds']['Pass'])
     self.THeaders['Url'].append(data['POSTCreds']['Url'])
     self.THeaders['Source/Destination'].append(data['POSTCreds']['Destination'])
     Headers = []
     self.setRowCount(len(self.THeaders['Username']))
     for n, key in enumerate(self.THeaders.keys()):
         Headers.append(key)
         for m, item in enumerate(self.THeaders[key]):
             item = QTableWidgetItem(item)
             item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
             self.setItem(m, n, item)
     self.setHorizontalHeaderLabels(self.THeaders.keys())
     self.verticalHeader().setDefaultSectionSize(27)
     self.scrollToBottom()
Esempio n. 31
0
 def writeModeData(self,data):
     ''' get data output and add on QtableWidgets '''
     self.THeaders['Username'].append(data['POSTCreds']['User'])
     self.THeaders['Password'].append(data['POSTCreds']['Pass'])
     self.THeaders['Url'].append(data['POSTCreds']['Url'])
     self.THeaders['Source/Destination'].append(data['POSTCreds']['Destination'])
     Headers = []
     self.setRowCount(len(self.THeaders['Username']))
     for n, key in enumerate(self.THeaders.keys()):
         Headers.append(key)
         for m, item in enumerate(self.THeaders[key]):
             item = QTableWidgetItem(item)
             item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
             self.setItem(m, n, item)
     self.setHorizontalHeaderLabels(self.THeaders.keys())
     self.verticalHeader().setDefaultSectionSize(27)
     self.scrollToBottom()
Esempio n. 32
0
    def __insertRow(self, repoName, repoAddress):
        currentRow = self.settings.repoListView.rowCount()
        self.settings.repoListView.insertRow(currentRow)
        checkbox = QCheckBox(self.settings.repoListView)
        self.connect(checkbox, SIGNAL("toggled(bool)"), self.markChanged)
        self.settings.repoListView.setCellWidget(currentRow, 0, checkbox)
        self.settings.repoListView.cellWidget(currentRow, 0).setChecked(self.iface.isRepoActive(repoName))

        repoNameItem = QTableWidgetItem()
        repoNameItem.setText(repoName)
        repoNameItem.setTextAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        self.settings.repoListView.setItem(currentRow, 1, repoNameItem)

        repoAddressItem = QTableWidgetItem()
        repoAddressItem.setText(repoAddress)
        repoAddressItem.setTextAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        self.settings.repoListView.setItem(currentRow, 2, repoAddressItem)
Esempio n. 33
0
  def refresh(self, dateSE, timeSE):
    if not self.sqlconn:
      self.sqlconn = sqlite3.connect(dbfile)
      self.curs = self.sqlconn.cursor()

    if not self.sqlconn or not self.curs:
      return

    ttype = "amounts_in" if str(self.parent.comboTrafType) == '0' else "amounts_out"
    q = "SELECT date,hour,amount FROM '{}' WHERE date > '{}'"
    q+= " AND date < '{}' AND hour > '{}' AND hour < '{}'"
    q = q.format(ttype, dateSE[0], dateSE[1], timeSE[0], timeSE[1])
    self.curs.execute(q)
    #print("debug", ttype, q)

    irow = 1
    fullsum = 0
    self.myclear()
    for row in self.curs:
      self.setRowCount(irow + 1)
      fullsum += row[2]
      d = QTableWidgetItem(str(row[0]))
      h = QTableWidgetItem("{:02}:00".format(row[1]))

      s = QTableWidgetItem(self.parent.comboTrafSize.calc(row[2]))
      i = self.parent.comboTrafType.items[int(str(self.parent.comboTrafType))][1]
      s.setIcon(QtGui.QIcon(join(ipath, i)))

      if not irow % 2 == 0:
        d.setBackgroundColor(self.backcolor)
        h.setBackgroundColor(self.backcolor)
        s.setBackgroundColor(self.backcolor)
      
      self.setItem(irow, 0, d)
      self.setItem(irow, 1, h)
      self.setItem(irow, 2, s)
      irow += 1

    s = QTableWidgetItem("Итого:")
    s.setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    self.setItem(0, 1, s)

    s = QTableWidgetItem(self.parent.comboTrafSize.calc(fullsum))
    s.setForeground(QtGui.QBrush(QtGui.QColor(244, 0, 0)))
    self.setItem(0, 2, s)
Esempio n. 34
0
    def table_item_changed(self):
        dict = {}
        message = ""
        error_row_index = -1
        error_column_index = -1
        previous_value = ""

        try:
            row_count = self.harmonic_maximum_index + 1

            for column_index in range(0, self.table.columnCount()):
                column_name = self.table.horizontalHeaderItem(column_index).data(0)

                row_content = []

                for row_index in range(0, row_count):
                    if not self.table.item(row_index, column_index) is None:
                        message = "Value at row " + str(
                            row_index) + " and column \'" + column_name + "\' is not numeric"
                        error_row_index = row_index
                        error_column_index = column_index
                        previous_value = self.data[column_name][row_index]

                        value = float(self.table.item(row_index, column_index).data(0))  # to raise exception

                        row_content.append(str(value))

                dict[column_name] = row_content

            self.data = dict
        except ValueError:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 message + "\nValue is reset to previous value",
                                 QMessageBox.Ok)

            table_item = QTableWidgetItem(previous_value)
            table_item.setTextAlignment(Qt.AlignRight)
            self.table.setItem(error_row_index, error_column_index, table_item)
            self.table.setCurrentCell(error_row_index, error_column_index)

        except Exception as exception:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 exception.args[0],
                                 QMessageBox.Ok)
Esempio n. 35
0
def set_col(table, row, col, val, fmt=None, color=None, align=None, editable=None, data=None):
	item = QTableWidgetItem(fmt % val if fmt else str(val))
	if color:
		item.setForeground(QtGui.QColor(color))
	if align=="right":
		item.setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
	if align=="center":
		item.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
	if not(editable is None):
		if editable:
			item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
				| QtCore.Qt.ItemIsEditable)
		else:
			item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
	if data:
		item.setData(99, data)
	
	table.setItem(row, col, item)
	return item
Esempio n. 36
0
    def addCorrector(self, idx):
        if not self._corlst1.selectedItems(): return
        #print self._corlst1.itemFromIndex(idx).text(0)
        nrow = self.table4.rowCount()
        if nrow >= self._nmax:
            QtGui.QMessageBox.critical(
                self, "Local Orbit Bump",
                "ERROR: We need only {0} correctors.".format(self._nmax),
                QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
            return
        self.table4.setRowCount(nrow+1)
        it0 = self._corlst1.selectedItems()[-1]
        icor, ok = it0.data(0, Qt.UserRole).toInt()
        if icor < 0: return
        newc = self._cors[icor]
        for j in range(self.table4.columnCount()):
            it = QTableWidgetItem()
            if j > 0: it.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            header = self.table4.horizontalHeaderItem(j)
            if header.text() != "dBump":
                it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            else:
                it.setData(Qt.DisplayRole, "0")
                it.setData(Qt.UserRole, 0.0)
            self.table4.setItem(nrow, j, it)
        self.table4.item(nrow,0).setData(Qt.UserRole, icor)
        for j,h in [(0, "Element"), (1, "s [m]")]:
            self.table4.item(nrow,j).setData(Qt.DisplayRole,
                                          it0.text(self._header[h]))
        for j in range(self._corlst1.columnCount()):
            it0.setForeground(j, Qt.red)
        it0.setDisabled(True)
        self.emit(SIGNAL("correctorAdded(PyQt_PyObject)"), newc)
        # use initial values

        self.updateTwiss()
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        if self.table4.rowCount() == self._nmax:
            #print "All correctors are ready"
            self.emit(SIGNAL("correctorsComplete()"))
Esempio n. 37
0
 def writeModeData(self,data):
     '''get data output and add on QtableWidgets '''
     Headers = []
     data = data.split()
     self.THeaders['IP Address'].append(data[0])
     self.THeaders['Method'].append(data[1])
     self.THeaders['Path'].append(data[2])
     self.setRowCount(len(self.THeaders['Path']))
     for n, key in enumerate(self.THeaders.keys()):
         Headers.append(key)
         for m, item in enumerate(self.THeaders[key]):
             item = QTableWidgetItem(item)
             if key == 'Path':
                 item.setIcon(QIcon('icons/accept.png'))
             else:
                 item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
             self.setItem(m, n, item)
     self.setHorizontalHeaderLabels(self.THeaders.keys())
     self.scrollToBottom()
Esempio n. 38
0
    def addCorrector(self, idx):
        if not self._corlst1.selectedItems(): return
        #print self._corlst1.itemFromIndex(idx).text(0)
        nrow = self.table4.rowCount()
        if nrow >= self._nmax:
            QtGui.QMessageBox.critical(
                self, "Local Orbit Bump", 
                "ERROR: We need only {0} correctors.".format(self._nmax),
                QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
            return
        self.table4.setRowCount(nrow+1)
        it0 = self._corlst1.selectedItems()[-1]
        icor, ok = it0.data(0, Qt.UserRole).toInt()
        if icor < 0: return
        newc = self._cors[icor]
        for j in range(self.table4.columnCount()):
            it = QTableWidgetItem()
            if j > 0: it.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            header = self.table4.horizontalHeaderItem(j)
            if header.text() != "dBump":
                it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            else:
                it.setData(Qt.DisplayRole, "0")
                it.setData(Qt.UserRole, 0.0)
            self.table4.setItem(nrow, j, it)
        self.table4.item(nrow,0).setData(Qt.UserRole, icor)
        for j,h in [(0, "Element"), (1, "s [m]")]:
            self.table4.item(nrow,j).setData(Qt.DisplayRole,
                                          it0.text(self._header[h]))
        for j in range(self._corlst1.columnCount()):
            it0.setForeground(j, Qt.red)
        it0.setDisabled(True)
        self.emit(SIGNAL("correctorAdded(PyQt_PyObject)"), newc)
        # use initial values

        self.updateTwiss()
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        if self.table4.rowCount() == self._nmax:
            #print "All correctors are ready"
            self.emit(SIGNAL("correctorsComplete()"))
Esempio n. 39
0
    def writeModeData(self, data):
        ''' get data output and add on QtableWidgets'''
        for name in self.pluginsName:
            if name in data:
                self.THeaders['Output'].append(data[len('[{}]'.format(name)):])
                self.THeaders['Plugin'].append('[{}]'.format(name))

        Headers = []
        self.setRowCount(len(self.THeaders['Plugin']))
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                item = QTableWidgetItem(item)
                if key == 'Plugin':
                    item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.setItem(m, n, item)
        self.setHorizontalHeaderLabels(list(self.THeaders.keys()))
        self.verticalHeader().setDefaultSectionSize(27)
        self.scrollToBottom()
Esempio n. 40
0
    def extend_rows(self):
        nb_rows = self.rowCount()
        self.setRowCount(nb_rows + 1)
        self.setSpan(nb_rows, 0, 1, 2)
        self.setItem(nb_rows, 2, QTableWidgetItem(u"Montant"))
        monttc = QTableWidgetItem(formatted_number(u"%d" % 0))
        monttc.setTextAlignment(Qt.AlignRight)
        self.setItem(nb_rows, 3, monttc)

        nb_rows += 1
        self.setRowCount(nb_rows + 1)
        self.setSpan(nb_rows, 0, 1, 3)
        self.button = Button_save(u"Enregistrer")
        self.button.released.connect(self.parent.save_b)
        self.setCellWidget(nb_rows, 3, self.button)

        pw = (self.parentWidget().width()) / 5
        self.setColumnWidth(0, pw)
        self.setColumnWidth(1, pw * 2)
Esempio n. 41
0
    def writeModeData(self,data):
        ''' get data output and add on QtableWidgets'''
        for name in self.pluginsName:
            if name in data:
                self.THeaders['Output'].append(data[len('[{}]'.format(name)):])
                self.THeaders['Plugin'].append('[{}]'.format(name))

        Headers = []
        self.setRowCount(len(self.THeaders['Plugin']))
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                item = QTableWidgetItem(item)
                if key == 'Plugin':
                    item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.setItem(m, n, item)
        self.setHorizontalHeaderLabels(self.THeaders.keys())
        self.verticalHeader().setDefaultSectionSize(27)
        self.scrollToBottom()
Esempio n. 42
0
 def writeModeData(self, data):
     '''get data output and add on QtableWidgets '''
     Headers = []
     data = data.split()
     self.THeaders['IP Address'].append(data[0])
     self.THeaders['Method'].append(data[1])
     self.THeaders['Path'].append(data[2])
     self.setRowCount(len(self.THeaders['Path']))
     for n, key in enumerate(self.THeaders.keys()):
         Headers.append(key)
         for m, item in enumerate(self.THeaders[key]):
             item = QTableWidgetItem(item)
             if key == 'Path':
                 item.setIcon(QIcon('icons/accept.png'))
             else:
                 item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
             self.setItem(m, n, item)
     self.setHorizontalHeaderLabels(self.THeaders.keys())
     self.scrollToBottom()
Esempio n. 43
0
    def populate_function_table_1(self):
        """Populate the tblFunctions1 table with available functions."""
        hazards = deepcopy(hazard_all)
        exposures = exposure_all

        self.lblAvailableFunctions1.clear()
        self.tblFunctions1.clear()
        self.tblFunctions1.setColumnCount(len(hazards))
        self.tblFunctions1.setRowCount(len(exposures))
        for i in range(len(hazards)):
            hazard = hazards[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(hazard)))
            item.setText(hazard['name'].capitalize())
            item.setTextAlignment(Qt.AlignLeft)
            self.tblFunctions1.setHorizontalHeaderItem(i, item)
        for i in range(len(exposures)):
            exposure = exposures[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(exposure)))
            item.setText(exposure['name'].capitalize())
            self.tblFunctions1.setVerticalHeaderItem(i, item)
        developer_mode = setting('developer_mode', False, bool)
        for hazard in hazards:
            for exposure in exposures:
                item = QTableWidgetItem()
                if (exposure in hazard['disabled_exposures']
                        and not developer_mode):
                    background_colour = unavailable_option_color
                    # Set it disable and un-selectable
                    item.setFlags(item.flags() & ~Qt.ItemIsEnabled
                                  & ~Qt.ItemIsSelectable)
                else:
                    background_colour = available_option_color
                item.setBackground(QBrush(background_colour))
                item.setFont(big_font)
                item.setTextAlignment(Qt.AlignCenter | Qt.AlignHCenter)
                item.setData(RoleHazard, hazard)
                item.setData(RoleExposure, exposure)
                self.tblFunctions1.setItem(exposures.index(exposure),
                                           hazards.index(hazard), item)
        self.parent.pbnNext.setEnabled(False)
Esempio n. 44
0
 def metaStateChanged(self, newState, oldState):
     if newState == Phonon.ErrorState:
         QMessageBox.warning(self.__main_window, "Error opening files",
                             self.__meta_information_resolver.errorString())
         while self.__list_music and self.__list_music.pop(
         ) != self.__meta_information_resolver.currentSource():
             pass
         return
     if newState != Phonon.StoppedState and newState != Phonon.PausedState:
         return
     if self.__meta_information_resolver.currentSource().type(
     ) == Phonon.MediaSource.Invalid:
         return
     metaData = self.__meta_information_resolver.metaData()
     title = metaData.get(QString('TITLE'), [''])[0]
     if not title:
         title = self.__meta_information_resolver.currentSource().fileName()
     artist = metaData.get(QString('ARTIST'), [''])[0]
     if artist:
         title = title + ' - ' + artist
     titleItem = QTableWidgetItem(title)
     titleItem.setFlags(titleItem.flags() ^ Qt.ItemIsEditable)
     titleItem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
     long_duration = self.__meta_information_resolver.totalTime()
     total_time_item = QTableWidgetItem(
         QTime(0, (long_duration / 60000) % 60,
               (long_duration / 1000) % 60).toString('mm:ss'))
     total_time_item.setFlags(total_time_item.flags() ^ Qt.ItemIsEditable)
     total_time_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     currentRow = self.__music_table.rowCount()
     self.__music_table.insertRow(currentRow)
     self.__music_table.setItem(currentRow, 0, titleItem)
     self.__music_table.setItem(currentRow, 1, total_time_item)
     if not self.__music_table.selectedItems():
         self.__music_table.selectRow(0)
         self.__media_object.setCurrentSource(
             self.__meta_information_resolver.currentSource())
     index = self.__list_music.index(
         self.__meta_information_resolver.currentSource()) + 1
     if len(self.__list_music) > index:
         self.__meta_information_resolver.setCurrentSource(
             self.__list_music[index])
Esempio n. 45
0
    def populateDefPolTable(self):
        # add data to defpol table and format it
        self.g_defpol.clear()
        self.g_defpol.setAlternatingRowColors(True)
        self.g_defpol.setSortingEnabled(False)
        self.g_defpol.setHorizontalHeaderLabels(["Value", "Type"])
        self.g_defpol.setRowCount(
            len(self.config.defpol_index[self.config.lenOrgDefPol:]))

        for i, it in enumerate(
                self.config.defpol_index[self.config.lenOrgDefPol:]):
            item = QTableWidgetItem()
            item.setText(it)
            self.g_defpol.setItem(i, 0, item)
            item2 = QTableWidgetItem()
            item2.setText(self.config.defpol[it])
            item2.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
            self.g_defpol.setItem(i, 1, item2)

        self.g_defpol.resizeColumnsToContents()
Esempio n. 46
0
    def extend_rows(self):

        pw = (self.parentWidget().width()) / (len(self.hheaders) + 2)
        # if pw == 14:
        #     pw = 125
        self.setColumnWidth(0, pw * 3)
        self.setColumnWidth(1, pw)
        self.setColumnWidth(2, pw)
        self.setColumnWidth(3, pw)
        self.setColumnWidth(4, pw)

        nb_rows = self.rowCount()
        self.setRowCount(nb_rows + 2)
        self.setSpan(nb_rows, 0, 2, 2)
        mtt_ttc = QTableWidgetItem(u"TOTAUX: ")
        mtt_ttc.setTextAlignment(Qt.AlignRight)
        self.setItem(nb_rows + 1, 2, mtt_ttc)

        self.montant_ht = 0
        self.montant_b = 0
        for row_num in xrange(0, self.data.__len__()):
            mtt = is_int(self.item(row_num, 3).text())
            mttb = is_int(self.item(row_num, 4).text())
            self.montant_ht += mtt
            self.montant_b += mttb
        # Montant TTC
        montant_t = QTableWidgetItem(formatted_number(self.montant_ht))
        montant_t.setTextAlignment(Qt.AlignRight)
        montant_tb = QTableWidgetItem(formatted_number(self.montant_b))
        montant_tb.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 2, 3, montant_t)
        self.setItem(row_num + 2, 4, montant_tb)
Esempio n. 47
0
    def extend_rows(self):

        pw = (self.parentWidget().width()) / (len(self.hheaders) + 2)
        # if pw == 14:
        #     pw = 125
        self.setColumnWidth(0, pw * 3)
        self.setColumnWidth(1, pw)
        self.setColumnWidth(2, pw)
        self.setColumnWidth(3, pw)
        self.setColumnWidth(4, pw)

        nb_rows = self.rowCount()
        self.setRowCount(nb_rows + 2)
        self.setSpan(nb_rows, 0, 2, 2)
        mtt_ttc = QTableWidgetItem(u"TOTAUX: ")
        mtt_ttc.setTextAlignment(Qt.AlignRight)
        self.setItem(nb_rows + 1, 2, mtt_ttc)

        self.montant_ht = 0
        self.montant_b = 0
        for row_num in xrange(0, self.data.__len__()):
            mtt = is_int(self.item(row_num, 3).text())
            mttb = is_int(self.item(row_num, 4).text())
            self.montant_ht += mtt
            self.montant_b += mttb
        # Montant TTC
        montant_t = QTableWidgetItem(formatted_number(self.montant_ht))
        montant_t.setTextAlignment(Qt.AlignRight)
        montant_tb = QTableWidgetItem(formatted_number(self.montant_b))
        montant_tb.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 2, 3, montant_t)
        self.setItem(row_num + 2, 4, montant_tb)
Esempio n. 48
0
    def _display_total_row(self, row_num=None):
        ''' adds the total row at end of table '''

        # display total row at end of table
        if self._display_total:

            if not row_num:
                row_num = self.data.__len__()

            # spans columns up to first data one
            # add label inside
            label_item = QTableWidgetItem(u"%s" % self._total_label)
            label_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.setItem(row_num, 0, label_item)
            self.setSpan(row_num, 0, 1, self._column_totals.keys()[0])
            # calculate total for each total column
            # if desired
            for index, total in self._column_totals.items():
                if not total:
                    total = sum([data[index] for data in self.data])
                item = QTableWidgetItem(self._format_for_table(total))
                self.setItem(row_num, index, item)
Esempio n. 49
0
File: ui.py Progetto: bindx/EE-Book
    def update_library(self):
        self.library = get_library()

        self.library_table.clear()
        self.library_table.setStyleSheet("selection-background-color: blue")  # 设置选中背景色
        self.library_table.setRowCount(len(self.library['books']))
        self.library_table.setColumnCount(5)    # TODO: 改掉硬编码??
        self.library_table.setHorizontalHeaderLabels(['Title', 'Authors', 'Tags', 'Date', 'Size(MB)'])

        self.library_table.setAlternatingRowColors(True)
        self.library_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.library_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.library_table.setSelectionMode(QTableWidget.SingleSelection)

        self.model = QtGui.QStandardItemModel(self)
        for i, book in enumerate(self.library['books']):
            for j, cell in enumerate((book['title'], book['author'], book['tags'],
                                      book['date'], book['size'])):
                item = QTableWidgetItem(cell)
                item.setTextAlignment(Qt.AlignCenter)
                self.library_table.setItem(i, j, item)

        self.library_table.resizeColumnsToContents()
Esempio n. 50
0
    def extend_rows(self):

        nb_rows = self.rowCount()
        self.setRowCount(nb_rows + 3)
        self.setSpan(nb_rows, 0, 3, 2)
        mtt_ttc = QTableWidgetItem(u"Total: ")
        mtt_ttc.setTextAlignment(Qt.AlignRight)
        self.setItem(nb_rows + 1, 2, mtt_ttc)

        montant_ht = 0
        for row_num in xrange(0, self.data.__len__()):
            quantity = is_int(self.item(row_num, 0).text())
            pu = is_int(self.item(row_num, 2).text())
            montant_ht += (quantity * pu)
        # Montant TTC
        montant_ttc = QTableWidgetItem(formatted_number(montant_ht))
        montant_ttc.setTextAlignment(Qt.AlignRight)
        self.setItem(row_num + 2, 3, montant_ttc)

        # bicon = QIcon.fromTheme('', QIcon(u"{}del.png".format(Config.img_media)))
        # self.button = QPushButton(bicon, u"Annuler la facture")
        self.button = Deleted_btt(u"Annuler la facture")
        self.button.released.connect(self.parent.annulation)
Esempio n. 51
0
    def refresh(self, data):
        i = 0
        tcp = "[((1,2),(1,2))]"
        dic_tcp = eval(tcp)
        for data in state.dic_tcp:
            if i >= self.grid.rowCount():
                self.grid.insertRow(i)
            ((sip, sport), (dip, dport)) = data
            newItem = QTableWidgetItem(str(sip))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 0, newItem)
            newItem = QTableWidgetItem(str(sport))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 1, newItem)
            newItem = QTableWidgetItem(str(dip))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 2, newItem)
            newItem = QTableWidgetItem(str(dport))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 3, newItem)
            newItem = QTableWidgetItem(u"检测中")
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 4, newItem)
            i += 1
        dic_tcp = eval(tcp)
        for data in state.ls_pro:
            if i >= self.grid.rowCount():
                self.grid.insertRow(i)
            (sip, sport) = data[0]
            newItem = QTableWidgetItem(str(sip))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 0, newItem)
            newItem = QTableWidgetItem(str(sport))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 1, newItem)
            newItem = QTableWidgetItem(u"等待禁止")
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 4, newItem)
            i += 1
        dic_tcp = eval(tcp)
        for data in state.ls_pro:
            if i >= self.grid.rowCount():
                self.grid.insertRow(i)
            (sip, sport) = data[0]

            newItem = QTableWidgetItem(str(sip))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 0, newItem)
            newItem = QTableWidgetItem(str(sport))
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 1, newItem)
            newItem = QTableWidgetItem(u"已禁止")
            newItem.setTextAlignment(0x004)
            self.grid.setItem(i, 4, newItem)
            i += 1

        if i < self.grid.rowCount():
            n = self.grid.rowCount()
            for j in range(i, n):
                self.grid.removeRow(i)
Esempio n. 52
0
  def onBlockRead(self, addr_start, num_bytes, raw_bytes):
    if addr_start == self.scan_addr_start and num_bytes == self.scan_num_bytes:
      # Validate txt_value
      res = parse_dec_or_hex(self.txt_value.getValue())
      if res is None:
        self.log.emit('Failed to parse Current Value: must be either DEC or HEX format', 'red')
        return
      elif res[0] < 0:
        self.log.emit('Failed to parse Current Value: must be positive', 'red')
        return
      if self.code.num_bytes == 1:
        value_bytes = struct.pack('>B', res[0])
      elif self.code.num_bytes == 2:
        value_bytes = struct.pack('>H', res[0])
      elif self.code.num_bytes == 4:
        value_bytes = struct.pack('>I', res[0])
      else:
        self.log.emit('INTERNAL ERROR: code has %d bytes' % self.code.num_bytes, 'red')
        return

      range_bytes = str(raw_bytes)
      if self.scan_count == 0: # List matching-valued addresses in initial scan
        self.cand_addrs = []
        byte_offset = 0
        while byte_offset < num_bytes:
          addr_curr = addr_start + byte_offset
          if range_bytes[byte_offset:(byte_offset+self.code.num_bytes)] == value_bytes:
            self.cand_addrs.append(addr_curr)
          byte_offset += self.code.num_bytes

      else: # Reduce matching-valued addresses in non-initial scan
        if len(self.cand_addrs) == 0:
          self.log.emit('No more candidate addresses remaining; press Reset instead', 'red')
          return
        idx = 0
        while idx < len(self.cand_addrs):
          addr_curr = self.cand_addrs[idx]
          byte_offset = addr_curr - addr_start
          if byte_offset < 0 or (byte_offset+self.code.num_bytes) > num_bytes:
            self.log.emit('INTERNAL ERROR: byte_offset (%d) out of range [0, %d)' % (byte_offset, num_bytes-self.code.num_bytes), 'red')
            return
          if range_bytes[byte_offset:(byte_offset+self.code.num_bytes)] == value_bytes:
            idx += 1
          else:
            self.cand_addrs.pop(idx)

      # Update scan count
      if self.scan_count == 0:
        self.txt_magn.setEnabled(False)
        self.btn_upd_range.setEnabled(False)
        self.txt_range_min.setEnabled(False)
        self.txt_range_max.setEnabled(False)
      self.scan_count += 1

      # Re-populate table
      exp_rows = len(self.cand_addrs)
      num_rows = self.tbl_cand.rowCount()
      if num_rows > exp_rows:
        for idx in xrange(num_rows-1, exp_rows-1, -1):
          self.tbl_cand.removeRow(idx)
      elif num_rows < exp_rows:
        for idx in xrange(num_rows, exp_rows):
          self.tbl_cand.insertRow(idx)
      for idx in xrange(exp_rows):
        cand_addr = self.cand_addrs[idx]
        item = QTableWidgetItem('%d' % (idx+1))
        item.setTextAlignment(Qt.AlignCenter)
        self.tbl_cand.setItem(idx, 0, item)

        item = QTableWidgetItem('0x%08X' % cand_addr)
        item.setTextAlignment(Qt.AlignCenter)
        self.tbl_cand.setItem(idx, 1, item)

        offset = cand_addr - self.code.addr_base
        item = QTableWidgetItem('%d (%s)' % (offset, to_signed_hex_str(offset)))
        item.setTextAlignment(Qt.AlignCenter)
        self.tbl_cand.setItem(idx, 2, item)

      self.log.emit('Offset scan found %d candidate addresses' % len(self.cand_addrs), 'black')
 def _getCenteredTableWidgetItem(self, text):
     item = QTableWidgetItem(text)
     item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     return item
Esempio n. 54
0
def make_widget(main, show=True):

    id = main.persistant['id']
    table = QTableWidget()
    table.controller = ROITableController(table, main)
    table.setGeometry(QRect(20, 33, 496, 296))
    table.setWindowTitle('ceilingfaan - ROI Table - Work in progress')
    analysis = s.query(Analysis).order_by(Analysis.date.desc()).all()
    table.setRowCount(len(analysis))
    table.setColumnCount(4)
    table.setHorizontalHeaderLabels(
        QString('CONTROL,DATE,MOUSE,FILENAME').split(','))

    current_analysis = None
    on_render = table.controller.on('render')
    on_import = table.controller.on('import')
    for nrow, entity in enumerate(analysis):
        if entity.id == id:
            print 'Found matching analysis data', id, 'at nrow:', nrow
            current_analysis = entity
            current_nrow = nrow
            continue

        for ncol, attr in enumerate('date mouse_id filename'.split()):
            field = getattr(entity, attr)
            item = QTableWidgetItem(str(field))
            item.setFlags(Qt.ItemIsEnabled)
            table.setItem(nrow, ncol + 1, item)

        render_btn = QPushButton('Render', checkable=True)
        render_btn.setStyleSheet('font-size: 9px; background-color: skyblue;')
        import_btn = QPushButton('Import')
        import_btn.setStyleSheet('font-size: 9px;')

        btn_layout = QHBoxLayout()
        btn_layout.setContentsMargins(5, 0, 5, 0)
        btn_layout.addWidget(render_btn)
        btn_layout.addWidget(import_btn)

        btn_widget = QWidget()
        btn_widget.nrow = nrow
        btn_widget.analysis_id = entity.id
        btn_widget.ext_roi_set = None
        btn_widget.setLayout(btn_layout)
        table.setCellWidget(nrow, 0, btn_widget)

        render_btn.clicked.connect(on_render)
        import_btn.clicked.connect(on_import)

    if current_analysis:
        table.removeRow(current_nrow)
        table.insertRow(0)
        item = QTableWidgetItem('Current Analysis')
        item.setFlags(Qt.ItemIsEnabled)
        item.setTextAlignment(Qt.AlignCenter)
        table.setItem(0, 0, item)
        for ncol, attr in enumerate('date mouse_id filename'.split()):
            field = getattr(current_analysis, attr)
            item = QTableWidgetItem(str(field))
            item.setFlags(Qt.ItemIsEnabled)
            table.setItem(0, ncol + 1, item)
        # debug.enter()

    table.setSelectionBehavior(QTableWidget.SelectRows)
    table.setSelectionMode(QTableWidget.NoSelection)
    table.resizeColumnsToContents()
    table.horizontalHeader().setStretchLastSection(True)

    if show: table.show()

    return table
class ProgressDialog(ProgressReporter, QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        super(ProgressReporter, self).__init__(parent)
        self.setupUi(self)
        self._currentTaskName = None
        self._currentTaskProgressBar = None
        self._currentTaskIncidents = None
        self._currentTaskIncidentsWidget = None
        self._currentTaskMessages = 0

        self.clear()

    def clear(self):
        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.output_text.clear()
        self.tableWidget.clear()

        self._currentTaskName = None
        self._currentTaskProgressBar = None
        self._currentTaskIncidents = None
        self._currentTaskIncidentsWidget = None
        self._currentTaskMessages = 0

        # Set up tablewidget
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setColumnCount(3)
        item = QTableWidgetItem()
        item.setText('Rule')
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        item.setText('Progress')
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem()
        item.setText('Incidents')
        self.tableWidget.setHorizontalHeaderItem(2, item)
        self.tableWidget.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        #self.tableWidget.horizontalHeader().setStretchLastSection(True)

    def enable_close(self):
        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)

    def add_message(self, text):
        self.output_text.appendPlainText(text)
        self.output_text.moveCursor(QTextCursor.End)
        self.output_text.ensureCursorVisible()

    def begintask(self, taskname, tasksize):
        self._begintask(taskname, tasksize)

    def completed(self, completed):
        QApplication.processEvents()
        super(ProgressDialog, self).completed(completed)

    def completed_all(self):
        pass

    def _report(self):
        percentcompleted = 100.0 * self.taskcompleted / self.tasksize if self.tasksize > 0 else 100
        self._currentTaskProgressBar.setValue(percentcompleted)
        QApplication.processEvents()

    def _begintask(self, taskname, tasksize):
        """Internal code when a new task is seen"""
        if taskname != self._currentTaskName:
            self._currentTaskName = taskname
            #item = QTableWidgetItem(taskname, "ProgressBar", "Count")
            rowPosition = self.tableWidget.rowCount(
            )  # necessary even when there are no rows in the table
            self.tableWidget.insertRow(rowPosition)
            self.tableWidget.setItem(rowPosition, 0,
                                     QTableWidgetItem(taskname))
            self._currentTaskProgressBar = QProgressBar()
            self.tableWidget.setCellWidget(rowPosition, 1,
                                           self._currentTaskProgressBar)
            self._currentTaskIncidentsWidget = QTableWidgetItem('0')
            self._currentTaskIncidentsWidget.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            self.tableWidget.setItem(rowPosition, 2,
                                     self._currentTaskIncidentsWidget)
            self.tableWidget.scrollToBottom()
            self._currentTaskIncidents = 0
            self._currentTaskMessages = 0

        super(ProgressDialog, self).begintask(taskname, tasksize)

    # Error reporter
    def error(self, rulename, typeinfo, message, geometry):
        self.report(rulename, typeinfo, message, geometry, 'ERROR')

    def warning(self, rulename, typeinfo, message, geometry):
        self.report(rulename, typeinfo, message, geometry, 'Warning')

    def report(self, rulename, typeinfo, message, geometry, level):
        if rulename != self._currentTaskName:
            self._begintask(rulename, -1)
        self._currentTaskIncidents += 1
        self._currentTaskIncidentsWidget.setText(
            str(self._currentTaskIncidents))
        if geometry is None:
            if self._currentTaskMessages == 0:
                self.add_message(
                    '-----------------------------------------------------------'
                )
                self.add_message('{} ({})'.format(self._currentTaskName,
                                                  str(typeinfo)))
                self.add_message(
                    '-----------------------------------------------------------'
                )
            self._currentTaskMessages += 1
            self.add_message('{}:\n{}'.format(level, message))
Esempio n. 56
0
    def __initializeUi(self):
        """
		Initializes the Widget ui.
		"""

        umbra.ui.common.setWindowDefaultIcon(self)

        LOGGER.debug("> Initializing '{0}' ui.".format(
            self.__class__.__name__))

        if Constants.applicationName not in self.__releases:
            self.sIBL_GUI_frame.hide()
            self.Get_sIBL_GUI_pushButton.hide()
        else:
            self.Logo_label.setPixmap(
                QPixmap(
                    os.path.join(self.__uiResourcesDirectory,
                                 self.__uiLogoImage)))
            self.Your_Version_label.setText(
                self.__releases[Constants.applicationName].localVersion)
            self.Latest_Version_label.setText(
                self.__releases[Constants.applicationName].repositoryVersion)
            self.Change_Log_webView.load(
                QUrl.fromEncoded(QByteArray(self.__applicationChangesUrl)))

        templatesReleases = dict(self.__releases)
        if Constants.applicationName in self.__releases:
            templatesReleases.pop(Constants.applicationName)

        if not templatesReleases:
            self.Templates_frame.hide()
            self.Get_Latest_Templates_pushButton.hide()
        else:
            self.Templates_label.setPixmap(
                QPixmap(
                    os.path.join(self.__uiResourcesDirectory,
                                 self.__uiTemplatesImage)))
            self.Templates_tableWidget.setParent(None)
            self.Templates_tableWidget = TemplatesReleases_QTableWidget(
                self, message="No Releases to view!")
            self.Templates_tableWidget.setObjectName("Templates_tableWidget")
            self.Templates_frame_gridLayout.addWidget(
                self.Templates_tableWidget, 1, 0)
            self.__view = self.Templates_tableWidget
            self.__view.clear()
            self.__view.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.__view.setRowCount(len(templatesReleases))
            self.__view.setColumnCount(len(self.__headers))
            self.__view.setHorizontalHeaderLabels(self.__headers)
            self.__view.hideColumn(0)
            self.__view.horizontalHeader().setStretchLastSection(True)

            palette = QPalette()
            palette.setColor(QPalette.Base, Qt.transparent)
            self.__view.setPalette(palette)

            verticalHeaderLabels = []
            for row, release in enumerate(sorted(templatesReleases)):
                verticalHeaderLabels.append(release)

                tableWidgetItem = QTableWidgetItem()
                tableWidgetItem.data = templatesReleases[release]
                self.__view.setItem(row, 0, tableWidgetItem)

                tableWidgetItem = Variable_QPushButton(
                    self, True,
                    (self.__uiLightGrayColor, self.__uiDarkGrayColor),
                    ("Yes", "No"))
                tableWidgetItem.setObjectName("Spread_Sheet_pushButton")
                self.__view.setCellWidget(row, 1, tableWidgetItem)

                tableWidgetItem = QTableWidgetItem(
                    templatesReleases[release].localVersion
                    or Constants.nullObject)
                tableWidgetItem.setTextAlignment(Qt.AlignCenter)
                self.__view.setItem(row, 2, tableWidgetItem)

                tableWidgetItem = QTableWidgetItem(
                    templatesReleases[release].repositoryVersion)
                tableWidgetItem.setTextAlignment(Qt.AlignCenter)
                self.__view.setItem(row, 3, tableWidgetItem)

                tableWidgetItem = QTableWidgetItem(
                    templatesReleases[release].type)
                tableWidgetItem.setTextAlignment(Qt.AlignCenter)
                self.__view.setItem(row, 4, tableWidgetItem)

                tableWidgetItem = QTableWidgetItem(
                    templatesReleases[release].comment)
                self.__view.setItem(row, 5, tableWidgetItem)

            self.__view.setVerticalHeaderLabels(verticalHeaderLabels)
            self.__view.resizeColumnsToContents()

        # Signals / Slots.
        self.Get_sIBL_GUI_pushButton.clicked.connect(
            self.__Get_sIBL_GUI_pushButton__clicked)
        self.Get_Latest_Templates_pushButton.clicked.connect(
            self.__Get_Latest_Templates_pushButton__clicked)
        self.Open_Repository_pushButton.clicked.connect(
            self.__Open_Repository_pushButton__clicked)
        self.Close_pushButton.clicked.connect(self.__Close_pushButton__clicked)