当前位置: 首页>>代码示例>>Python>>正文


Python QTableWidget.rowCount方法代码示例

本文整理汇总了Python中PyQt5.QtWidgets.QTableWidget.rowCount方法的典型用法代码示例。如果您正苦于以下问题:Python QTableWidget.rowCount方法的具体用法?Python QTableWidget.rowCount怎么用?Python QTableWidget.rowCount使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtWidgets.QTableWidget的用法示例。


在下文中一共展示了QTableWidget.rowCount方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: saveZotero

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
 def saveZotero(self):
     #Write what happens to save to zotero here
     rows = list(range(0, QTableWidget.rowCount(self.dlgTable.tableWidget_Zotero)))
     for row in rows:
         #get the itemID(zotero key) and geometry cells from the table - itemAt(x,y)
         itemKey = self.dlgTable.tableWidget_Zotero.item(row, 0).text()
         
         request_url = 'https://api.zotero.org/users/%s/items/%s' % (self.userID, itemKey)
         item_request = requests.get(request_url)
         QgsMessageLog.logMessage("Item Request Response: %s" % item_request.status_code, 'LiteratureMapper', Qgis.Info)
         item_json = json.load(urllib.request.urlopen(request_url))
         
         #Put the extra string back together with the new coordinates
         tablegeom = self.dlgTable.tableWidget_Zotero.item(row, 4).text()
         extraZotero = item_json['data']['extra']
         before_geojson = extraZotero[0 : extraZotero.find("<geojson>")]
         after_geojson = extraZotero[extraZotero.find("</geojson>")+10:]
         extraString = '%s<geojson>%s</geojson>%s' % (before_geojson, tablegeom, after_geojson) #build the new extraString here
         
         QgsMessageLog.logMessage("row: %s  itemKey: %s  extraString: %s" % (row, itemKey, extraString), 'LiteratureMapper', Qgis.Info)
         
         
         ####### saving Extra field
         item_json['data']['extra'] = extraString
         item_json=json.dumps(item_json)
         put_request = requests.put(request_url, data=item_json, headers={'Authorization': 'Bearer %s' % (self.apiKey), 'Content-Type': 'application/json'})
         QgsMessageLog.logMessage("Put Response: %s" % put_request.status_code, 'LiteratureMapper', Qgis.Info)
         statuscode = put_request.status_code
     # Message bar for result
     # TODO: make it check all the results, not just the last one
     if statuscode == 204:
         self.iface.messageBar().pushMessage("Locations saved to Zotero.", level=4)
         #QMessageBox.information(self.dlgTable(),"Info", "Locations Saved")
     else:
         self.iface.messageBar().pushMessage("Failed to save locations to Zotero", level=3)
开发者ID:MicheleTobias,项目名称:LiteratureMapper,代码行数:37,代码来源:literature_mapper.py

示例2: create_diff_table

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
    def create_diff_table(self, diffs):
        tbl = QTableWidget()
        tbl.setRowCount(len(diffs))
        tbl.setColumnCount(3)

        tbl.setHorizontalHeaderItem(0, QTableWidgetItem('Field'))
        tbl.setHorizontalHeaderItem(1, QTableWidgetItem('Current'))
        tbl.setHorizontalHeaderItem(2, QTableWidgetItem('Previous'))

        from PyQt5.QtGui import QColor
        red = QColor()
        red.setRed(255)

        for row, diff in enumerate(diffs):
            tbl.setItem(row, 0, QTableWidgetItem(diff.field_name))
            item1 = QTableWidgetItem(to_money(diff.current_amount))
            item2 = QTableWidgetItem(to_money(diff.previous_amount))
            if self._significant_diff(diff.current_amount, diff.previous_amount):
                item1.setForeground(red)
                item2.setForeground(red)
            tbl.setItem(row, 1, item1)
            tbl.setItem(row, 2, item2)

        tbl.verticalHeader().setVisible(False)
        tbl.resizeColumnsToContents()
        ht = tbl.rowHeight(0) * (tbl.rowCount() + 1)

        tbl.setFixedSize(tbl.horizontalHeader().length() + 20, ht)
        return tbl
开发者ID:Davincier,项目名称:payrun,代码行数:31,代码来源:paydiffs_widget.py

示例3: GEdges

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
class GEdges(QGraphicsLineItem):
    def __init__(self, x1, y1, x2, y2):
        QGraphicsEllipseItem.__init__(self, x1, y1, x2, y2)
        self.point_to = 0
        self.point_from = 0
        self.path_point = 0
        self.path_point_to = 0
        self.tbl = QTableWidget(1, 2)
        item = QTableWidgetItem("0:00")
        self.tbl.setItem(0, 0, item)
        item = QTableWidgetItem("0:00")
        self.tbl.setItem(0, 1, item)
        self.tbl.setFixedWidth(219)
        item = QTableWidgetItem("time of origin")
        self.tbl.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem("path time")
        self.tbl.setHorizontalHeaderItem(1, item)

    def save_points(self):
        self.point_from.out_edges.append(self)
        self.point_to.in_edges.append(self)

    def mouseDoubleClickEvent(self, event):
        if event.button() == Qt.LeftButton:
            print("RDACT!")

    def set_point_to(self, point):
        self.point_to = point

    def set_point_from(self, point):
        self.point_from = point

    def weight(self, time):
        for i in range(0, self.tbl.rowCount()):
            if datetime.datetime.strptime(self.tbl.item(i, 0).text(), "%H:%M") > time:
                return datetime.datetime.strptime(self.tbl.item(i, 1).text(), "%H:%M")+datetime.timedelta(hours=datetime.datetime.strptime(self.tbl.item(i, 0).text(), "%H:%M").hour, minutes=datetime.datetime.strptime(self.tbl.item(i, 0).text(), "%H:%M").minute)-datetime.timedelta(hours=time.hour, minutes=time.minute)
        return datetime.datetime.strptime("14:28", "%H:%M")

    def save_info(self, tbl):
        self.tbl = tbl
开发者ID:makaronnik13,项目名称:pathfinder,代码行数:42,代码来源:GEdges.py

示例4: Labels

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]

#.........这里部分代码省略.........
            self.setEnabled(True)
            self.chan_name = labels

        self.table.blockSignals(True)
        self.table.clearContents()
        self.table.setRowCount(len(self.chan_name))

        for i, label in enumerate(self.chan_name):
            old_label = QTableWidgetItem(label)
            old_label.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

            if custom_labels is not None and i < len(custom_labels) and custom_labels[i]:  # it's not empty string or None
                label_txt = custom_labels[i]
            else:
                label_txt = label
            new_label = QTableWidgetItem(label_txt)

            self.table.setItem(i, 0, old_label)
            self.table.setItem(i, 1, new_label)

        self.table.blockSignals(False)

    def check_labels(self):

        # read new labels first
        labels = self._read_labels()

        # disable apply, if there are duplicates
        if len(labels) == len(set(labels)):
            self.idx_apply.setEnabled(True)
        else:
            self.idx_apply.setEnabled(False)

        # mark duplicates in red
        self.table.blockSignals(True)
        for i, label in enumerate(labels):
            if labels.count(label) > 1:
                 self.table.item(i, 1).setBackground(QColor('red'))
            else:
                 self.table.item(i, 1).setBackground(QColor('white'))
        self.table.blockSignals(False)

    def load_labels(self, checked=False, test_name=None):
        if self.filename is not None:
            filename = self.filename
        elif self.parent.info.filename is not None:
            filename = Path(self.parent.info.filename)
        else:
            filename = None

        if test_name:
            filename = test_name
        else:
            filename, _ = QFileDialog.getOpenFileName(self,
                                                      'Open Labels',
                                                      str(filename.parent),
                                                      'Comma-separated values (*.csv);; Text file (*.txt);; All Files(*.*)')
        if filename == '':
            return

        self.filename = Path(filename)

        with self.filename.open() as f:
            text = f.read()

        labels = split(', |,|; |;|\t|\n| ',text)
        labels  = [label.strip() for label in labels]
        self.update(custom_labels=labels)

    def save_labels(self):
        """Save labels modified by the user.

        TODO
        ----
        Save labels modified by the user
        """
        pass

    def apply(self):

        self.chan_name = self._read_labels()
        self.parent.info.dataset.header['chan_name'] = self.chan_name

        self.parent.channels.reset()
        self.parent.traces.reset()

    def reset(self):
        self.table.blockSignals(True)
        self.table.clearContents()
        self.table.blockSignals(False)

        self.setEnabled(False)

    def _read_labels(self):

        labels = []
        for i in range(self.table.rowCount()):
            labels.append(self.table.item(i, 1).text())

        return labels
开发者ID:gpiantoni,项目名称:phypno,代码行数:104,代码来源:labels.py

示例5: MMWindow

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]

#.........这里部分代码省略.........
        self.update_media_files_status()

    def output_directory(self):
        """Choose output directory."""
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        directory = QFileDialog.getExistingDirectory(
            self,
            self.tr('Choose Output Directory'),
            QDir.homePath(),
            options=options)

        if directory:
            self.le_output.setText(directory)

    def add_media(self):
        """Add media files to the list of conversion tasks."""
        # Dialog title
        title = self.tr('Select Files')
        # Media filters
        v_filter = (self.tr('Video files') +
                    '(*.mkv *.ogg *.mp4 *.mpg *.dat '
                    '*.f4v *.flv *.wv *.3gp *.avi *.webm '
                    '*.wmv *.mov *.vob *.ogv *.ts)')
        # Select media files and store their path
        media_paths, _ = QFileDialog.getOpenFileNames(self,
                                                      title,
                                                      QDir.homePath(),
                                                      v_filter)
        # If no file is selected then return
        if not media_paths:
            return

        # Count rows in the tasks table
        rows = self.tb_tasks.rowCount()

        # This rewind the encoding list if the encoding process is not running
        if not self.converter.is_running:
            self.media_list.running_index = -1
        # Add selected medias to the table and to MediaList using threads to
        # minimize delay
        threads = []
        for media_path in media_paths:

            t = MediaFileThread(
                media_path=media_path,
                target_quality=str(self.cb_presets.currentText()),
                prober=self.get_prober())
            t.start()
            threads.append(t)

        for t in threads:
            t.join()

        for thread in threads:

            try:
                self.media_list.add_file(thread.media_file)
                self.tb_tasks.setRowCount(rows + 1)
            except FileAddedError:
                del thread.media_file
                continue
            # Test if the file was added to the list
            # (0 duration files are not added)
            if thread.media_file in self.media_list:
                item = QTableWidgetItem()
                item.setText(thread.media_file.get_name(with_extension=True))
开发者ID:codeshard,项目名称:videomorph,代码行数:70,代码来源:videomorph.py

示例6: DropSiteWindow

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
class DropSiteWindow(QWidget):

    def __init__(self):
        super(DropSiteWindow, self).__init__()

        self.abstractLabel = QLabel(
                "This example accepts drags from other applications and "
                "displays the MIME types provided by the drag object.")
        self.abstractLabel.setWordWrap(True)
        self.abstractLabel.adjustSize()

        self.dropArea = DropArea()
        self.dropArea.changed.connect(self.updateFormatsTable)

        self.formatsTable = QTableWidget()
        self.formatsTable.setColumnCount(2)
        self.formatsTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.formatsTable.setHorizontalHeaderLabels(["Format", "Content"])
        self.formatsTable.horizontalHeader().setStretchLastSection(True)

        self.clearButton = QPushButton("Clear")
        self.quitButton = QPushButton("Quit")

        self.buttonBox = QDialogButtonBox()
        self.buttonBox.addButton(self.clearButton, QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        self.quitButton.pressed.connect(self.close)
        self.clearButton.pressed.connect(self.dropArea.clear)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.abstractLabel)
        mainLayout.addWidget(self.dropArea)
        mainLayout.addWidget(self.formatsTable)
        mainLayout.addWidget(self.buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Drop Site")
        self.setMinimumSize(350, 500)

    def updateFormatsTable(self, mimeData=None):
        self.formatsTable.setRowCount(0)

        if mimeData is None:
            return

        for format in mimeData.formats():
            formatItem = QTableWidgetItem(format)
            formatItem.setFlags(Qt.ItemIsEnabled)
            formatItem.setTextAlignment(Qt.AlignTop | Qt.AlignLeft)

            if format == 'text/plain':
                text = mimeData.text().strip()
            elif format == 'text/html':
                text = mimeData.html().strip()
            elif format == 'text/uri-list':
                text = " ".join([url.toString() for url in mimeData.urls()])
            else:
                text = " ".join(["%02X" % ord(datum) for datum in mimeData.data(format)])

            row = self.formatsTable.rowCount()
            self.formatsTable.insertRow(row)
            self.formatsTable.setItem(row, 0, QTableWidgetItem(format))
            self.formatsTable.setItem(row, 1, QTableWidgetItem(text))

        self.formatsTable.resizeColumnToContents(0)
开发者ID:death-finger,项目名称:Scripts,代码行数:68,代码来源:dropsite.py

示例7: RowControlTableWidget

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
class RowControlTableWidget(QWidget):
    def __init__(self, items = [('col1_name', 'default text'), ('col2_name', ['dfeault', 'combo', 'elements'])]):
        super(RowControlTableWidget, self).__init__()
        self.ordered_column_keys = [ z[0] for z in items ]
        self.default_row = { z[0]:z[1] for z in items }
        self.table = QTableWidget(1, len(items))
        self.table.setHorizontalHeaderLabels(self.ordered_column_keys)
        self.add_row_button = QPushButton('Add Row')
        self.add_row_button.clicked.connect(self.add_row)
        self.delete_row_button = QPushButton('Delete Row')
        self.delete_row_button.clicked.connect(self.delete_row)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0,0,0,0)
        hbox.addWidget(self.add_row_button)
        hbox.addWidget(self.delete_row_button)

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0,0,0,0)
        self.layout.addLayout(hbox)
        self.layout.addWidget(self.table)

    def reset_row_template(self, items = [('col1_name', 'default text'), ('col2_name', ['dfeault', 'combo', 'elements'])]):
        # use to (re)set the values of the drop down elements inside the table cells
        self.ordered_column_keys = [ z[0] for z in items ]
        self.default_row = { z[0]:z[1] for z in items }

    def add_row(self):
        new_row_number = self.table.rowCount()
        self.table.setRowCount(self.table.rowCount()+1)

        for column, key in enumerate(self.ordered_column_keys):
                value = self.default_row[key]
                # print(value, type(value))
                if isinstance(value, str):
                    item = QTableWidgetItem(value)
                    self.table.setItem(new_row_number, column, item)
                elif isinstance(value, list):
                    combo_box = QComboBox()
                    combo_box.insertItems(0, value)
                    # combo_box.setCurrentText(value[0])
                    self.table.setCellWidget(new_row_number, column, combo_box)
                else:
                    message = 'Table cells are expected to be either Dict (added asQComboBox via setCellWidget) or String (added as QTableWidgetItem). You have type ' + str(type(value))
                    message += ' at position ' + str(new_row_number) + ', ' + str(column)
                    raise CellObjectException(message)

    def delete_row(self):
        self.table.removeRow(self.table.currentRow())

    def show(self):
        self.table.show()
        self.add_row_button.show()
        self.delete_row_button.show()

    def hide(self):
        self.table.hide()
        self.add_row_button.hide()
        self.delete_row_button.hide()

    def set_text(self, items):
        # where items should be list of lists of objects that can be either dict (loads as QComboBox) or string (used in setItem)
        # print('siphon itmes', items)
        self.table.setRowCount(len(items))
        self.table.setColumnCount(len(items[0]))
        for i, row in enumerate(items):
            # print('siphon row', row)
            for j, value in enumerate(row):
                if isinstance(value, str):
                    item = QTableWidgetItem(value)
                    self.table.setItem(i, j, item)
                elif isinstance(value, dict):
                    combo_box = QComboBox()
                    dict_keys = list(value.keys())
                    selected = dict_keys[0]
                    if isinstance(value[selected], dict):
                        combo_box.insertItems(0, list(value[selected].values()))
                    else:
                        combo_box.insertItems(0, value[selected])
                    combo_box.setCurrentText(selected)
                    self.table.setCellWidget(i, j, combo_box)
                else:
                    message = 'Table cells are expected to be either Dict (added asQComboBox via setCellWidget) or String (added as QTableWidgetItem). You have type ' + str(type(value))
                    message += ' at position ' + str(i) + ', ' + str(j)
                    raise CellObjectException(message)

    def get_values(self):
        table = []
        for i in range(self.table.rowCount()):
            row = []
            for j in range(self.table.columnCount()):
                try:
                    row.append(self.table.item(i, j).text())
                except AttributeError:
                    row.append(self.table.cellWidget(i, j).currentText())
            table.append(row)
        return table
开发者ID:bobev18,项目名称:stujeditor,代码行数:98,代码来源:gui_classes.py

示例8: WinList

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
class WinList(QWidget):
    def __init__(self, controller):
        super().__init__()
        self.controller = controller
        self.controller.addObserver(self)
        self.initUI()
        

    def initUI(self):
        self.setGeometry(200,200,600,280)
        self.setWindowTitle('Tag Indexer: List')
        
        self.tab = QTableWidget(self)
        self.tab.showGrid = False
        
        self.tab.horizontalHeader().setSectionResizeMode(1)
        self.tab.setColumnCount(3)
        self.tab.cellChanged.connect(self.getMod)
    
        lblRecherche = QLabel('Recherche: ', self)

        btnRecherche = QPushButton('Rechercher', self)
        btnRecherche.clicked.connect(self.rechercher)
        
        self.recherche = QLineEdit()
        self.recherche.returnPressed.connect(self.rechercher)

        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(lblRecherche, 0,0)
        grid.addWidget(btnRecherche, 0, 8)
        grid.addWidget(self.recherche, 0, 1, 1, 7)
        grid.addWidget(self.tab,4,0, 6,9)
        

        self.tab.setHorizontalHeaderLabels(('URL','Tags','Date d\'ajout'))
        self.setLayout(grid)
        
        self.controller.notify(GetAllEvent())

    def addLine(self, url, tags, date):
        l = self.tab.rowCount()
        self.tab.setRowCount(l+1)
        self.tab.setItem(l, 0, QTableWidgetItem(url))
        self.tab.setItem(l, 1, QTableWidgetItem(tags))
        self.tab.setItem(l, 2, QTableWidgetItem(date))
        
    def vider(self):
        self.tab.setRowCount(0)
        
    def rechercher(self):
        self.vider()
        s = self.recherche.text()
        if s == "":
            e = GetAllEvent()
        else:
            e = SearchEvent(s)
        self.controller.notify(e)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.hide()

    def closeEvent(self, e):
        self.hide()
        e.ignore()

    def notify(self, e):
        if type(e) is UpdateListEvent:
            if e.add:
                self.addLine(e.data, ', '.join(e.tags), e.date)
            

    def getMod(self):
        if(self.tab.currentRow(), self.tab.currentColumn()) != (-1, -1):
            print(self.tab.currentRow(),self.tab.currentColumn(),self.tab.currentItem().text())
开发者ID:L3nn0x,项目名称:tags,代码行数:78,代码来源:GUI.py

示例9: HistoryCertification

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]

#.........这里部分代码省略.........

        linha = 0
        for cada_equipamento in self.filtro_tabela:
            item = self.tableWidget.item(linha, 0)
            item.setText(cada_equipamento.trace_number)

            item = self.tableWidget.item(linha, 1)
            item.setText(cada_equipamento.linha_servico)

            item = self.tableWidget.item(linha, 2)
            item.setText(str(cada_equipamento.equipamento))

            item = self.tableWidget.item(linha, 3)
            item.setText(str(cada_equipamento.data_evento.date().strftime('%d-%m-%Y')))

            item = self.tableWidget.item(linha, 4)
            item.setText(str(cada_equipamento.evento))

            item = self.tableWidget.item(linha, 5)
            item.setText(str(cada_equipamento.numero_documento))

            linha+=1

    def ver_equipamento(self):
        print("Entrei aqui")
        tela_ver_equipamento = HistoryView()
        linha = self.tableWidget.currentRow()
        numero_documento = self.tableWidget.item(linha,5).text()
        tela_ver_equipamento.carrega_dados(numero_documento)
        tela_ver_equipamento.exec()

    def gerar_export_excel(self):
        # Leitura da TableWidget da tela do programa
        if self.tableWidget.rowCount()== 0:
            QMessageBox.about(self,'Warning','Tabela de dados inexistente')
            return  None
        lista_tabela = list()
        cabecalhos = list()
        index_coluna = 0
        while index_coluna < self.tableWidget.columnCount():
            cabecalhos.append(self.tableWidget.horizontalHeaderItem(index_coluna).text())
            index_coluna = index_coluna + 1
        lista_tabela.append(cabecalhos)
        index_linha = 0
        while index_linha < self.tableWidget.rowCount():
            index_coluna = 0
            linha = list()
            while index_coluna < self.tableWidget.columnCount():
                if self.tableWidget.item(index_linha,index_coluna) != None:
                    linha.append(self.tableWidget.item(index_linha,index_coluna).text())
                else:
                    linha.append('-')
                index_coluna += 1
            lista_tabela.append(linha)
            index_linha += 1
        exportar = ExcelExport()
        exportar.exportacao(lista_tabela)
        QMessageBox.about(self,'Message','Arquivo exportado com sucesso')

    def gerar_relatorio_historico(self):
        if len(self.filtro_tabela) == 0 :
            QMessageBox.about(self,'Warning','Dados insuficientes para gerar relatório!')
            return None

        if len(self.filtro_tabela) > 0 :
开发者ID:losimonassi,项目名称:Searchfication,代码行数:69,代码来源:File_History_Certification.py

示例10: HyperLprWindow

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]

#.........这里部分代码省略.........
        if len(self.hyperlpr_dir_path) > 0:
            hyperlpr_dir_info_filepath = QDir.homePath() + "/hyperlpr_dir_file"
            with open(hyperlpr_dir_info_filepath, 'w') as f:
                f.write(self.hyperlpr_dir_path)
            self.reset_info_gui()

    def rename_current_image_with_info(self):
        if len(self.hyperlpr_dir_path) > 0:
            target_dir_path = self.hyperlpr_dir_path + "/result"
            if not os.path.exists(target_dir_path):
                os.makedirs(target_dir_path)
            if len(self.plate_color_edit.text())>0 and len(self.e2e_recognization_edit.text())>0:
                orign_path = os.path.join(self.hyperlpr_dir_path, self.filename_edit.text())
                target_path = os.path.join(target_dir_path,self.plate_color_edit.text()+"-"+self.e2e_recognization_edit.text()+".jpg")
                shutil.copyfile(orign_path, target_path)

    def reset_info_gui(self):

        self.location_text.setText(self.hyperlpr_dir_path)
        self.scan_files_with_new_dir(self.hyperlpr_dir_path)
        self.fill_table_with_new_info()

    def scan_files_with_new_dir(self, path):

        name_list = os.listdir(path)  # 列出文件夹下所有的目录与文件
        self.image_filename_list.clear()
        for i in range(0, len(name_list)):
            if name_list[i].endswith(
                    ".jpg") or name_list[i].endswith(".png"):
                self.image_filename_list.append(name_list[i])

    def fill_table_with_new_info(self):
        self.hyperlpr_tableview.clearContents()
        row_count = self.hyperlpr_tableview.rowCount()
        for i in range(row_count, -1, -1):
            self.hyperlpr_tableview.removeRow(i)

        for i in range(0, len(self.image_filename_list)):
            row = self.hyperlpr_tableview.rowCount()
            self.hyperlpr_tableview.insertRow(row)

            item0 = QTableWidgetItem()
            item0.setTextAlignment(Qt.AlignCenter)
            self.hyperlpr_tableview.setItem(row, 0, item0)
            self.hyperlpr_tableview.item(
                row, 0).setText(
                self.image_filename_list[i])

            item1 = QTableWidgetItem()
            item1.setTextAlignment(Qt.AlignCenter)
            self.hyperlpr_tableview.setItem(row, 1, item1)

            item2 = QTableWidgetItem()
            item2.setTextAlignment(Qt.AlignCenter)
            self.hyperlpr_tableview.setItem(row, 2, item2)

            item3 = QTableWidgetItem()
            item3.setTextAlignment(Qt.AlignCenter)
            self.hyperlpr_tableview.setItem(row, 3, item3)

            item4 = QTableWidgetItem()
            item4.setTextAlignment(Qt.AlignCenter)
            self.hyperlpr_tableview.setItem(row, 4, item4)

            item5 = QTableWidgetItem()
            item5.setTextAlignment(Qt.AlignCenter)
开发者ID:han1157,项目名称:HyperLPR,代码行数:70,代码来源:HyperLprGUI.py

示例11: PairingsWidget

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
class PairingsWidget(QWidget):
	def __init__(self, parent):
		super(PairingsWidget, self).__init__(parent)
		self.parent = parent

		view.notifier.observers.append(self)

		self.header_label = QLabel('Pairings')

		self.header_widget = QWidget(self)
		header_layout = QBoxLayout(QBoxLayout.TopToBottom)
		header_layout.addWidget(self.header_label)
		self.header_widget.setLayout(header_layout)

		self.pairings_list = QTableWidget(style.style_loader.TABLE_INITIAL_LENGTH, 2, self)
		self.pairings_list.setFixedHeight(300)
		self.pairings_list.setFixedWidth(400)
		self.pairings_list.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
		self.pairings_list.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

		self.pairings_list_widget = QWidget(self)
		pairings_list_layout = QBoxLayout(QBoxLayout.LeftToRight)
		pairings_list_layout.addWidget(self.pairings_list)
		self.pairings_list_widget.setLayout(pairings_list_layout)

		self.report_btn = QPushButton('Report Results', self)
		self.report_btn.clicked.connect(parent.show_report_result_widget)

		self.report_btn_widget = QWidget(self)
		report_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		report_btn_layout.addWidget(self.report_btn)
		self.report_btn_widget.setLayout(report_btn_layout)

		layout = QFormLayout()
		layout.addRow(self.header_widget)
		layout.addRow(self.pairings_list_widget)
		layout.addRow(self.report_btn_widget)
		self.setLayout(layout)

		self.update()

	def update(self):
		self.pairings_list.clearContents()

		index = 0
		for p1, p2 in to.pairings.items():
			if index == self.pairings_list.rowCount():
				self.pairings_list.insertRow(index)
			p1_item = QTableWidgetItem(p1)
			p1_item.setFlags(p1_item.flags() & ~Qt.ItemIsEditable)
			self.pairings_list.setItem(index, 0, p1_item)
			if p2 == None:
				p2_str = '--BYE--'
			else:
				p2_str = p2
			p2_item = QTableWidgetItem(p2_str)
			p2_item.setFlags(p2_item.flags() & ~Qt.ItemIsEditable)
			self.pairings_list.setItem(index, 1, p2_item)
			index += 1
		self.pairings_list.show()

	def player_added(self, player, user):
		pass

	def player_removed(self, player):
		pass

	def pairings_created(self):
		self.update()
		self.parent.show()

	def report_result(self, player, record, win_loss_draw):
		try:
			if win_loss_draw == 'win':
				to.record_win(player, record)
			elif win_loss_draw == 'loss':
				to.record_loss(player, record)
			elif win_loss_draw == 'draw':
				to.record_draw(player, record)
			view.notifier.result_reported()
		except TournamentException as ex:
			self.error = ErrorMessage(str(ex), '')
			self.error.setStyleSheet(style.style_loader.stylesheet)
			self.error.show()

	def result_reported(self):
		self.update()
		self.parent.show()

	def reset(self):
		self.update()
		self.parent.show()
开发者ID:zlohner,项目名称:TournamentOrganizer,代码行数:94,代码来源:pairings_widget.py

示例12: UserManagerWidget

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
class UserManagerWidget(QWidget):
	def __init__(self, parent):
		super(UserManagerWidget, self).__init__(parent)
		self.parent = parent

		self.sort_order = 'by_name'

		view.notifier.observers.append(self)

		self.header_label = QLabel('Users')

		self.header_widget = QWidget(self)
		header_layout = QBoxLayout(QBoxLayout.LeftToRight)
		header_layout.addWidget(self.header_label)
		self.header_widget.setLayout(header_layout)

		self.sort_by_name_btn = QPushButton('Sort by Name', self)
		self.sort_by_name_btn.clicked.connect(self.sort_by_name)
		self.sort_by_rank_btn = QPushButton('Sort by Rank', self)
		self.sort_by_rank_btn.clicked.connect(self.sort_by_rank)

		self.sort_btns_widget = QWidget(self)
		sort_btns_layout = QBoxLayout(QBoxLayout.LeftToRight)
		sort_btns_layout.addWidget(self.sort_by_name_btn)
		sort_btns_layout.addSpacing(10)
		sort_btns_layout.addWidget(self.sort_by_rank_btn)
		self.sort_btns_widget.setLayout(sort_btns_layout)

		self.user_list = QTableWidget(style.style_loader.TABLE_INITIAL_LENGTH, 3, self)
		self.user_list.setFixedHeight(300)
		self.user_list.setFixedWidth(400)
		self.user_list.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
		self.user_list.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

		self.user_list_widget = QWidget(self)
		user_list_layout = QBoxLayout(QBoxLayout.LeftToRight)
		user_list_layout.addWidget(self.user_list)
		self.user_list_widget.setLayout(user_list_layout)

		self.add_player_btn = QPushButton('Add User', self)
		self.add_player_btn.clicked.connect(self.parent.show_add_user_widget)
		self.remove_player_btn = QPushButton('Remove User', self)
		self.remove_player_btn.clicked.connect(self.parent.show_remove_user_widget)

		self.player_btns_widget = QWidget(self)
		player_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		player_btn_layout.addWidget(self.add_player_btn)
		player_btn_layout.addSpacing(10)
		player_btn_layout.addWidget(self.remove_player_btn)
		self.player_btns_widget.setLayout(player_btn_layout)

		self.error = None

		layout = QFormLayout()
		layout.addRow(self.header_widget)
		layout.addRow(self.sort_btns_widget)
		layout.addRow(self.user_list_widget)
		layout.addRow(self.player_btns_widget)
		self.setLayout(layout)

		self.update()

	def update(self):
		self.user_list.clearContents()
		# TODO: get the most recent user list
		users = um.users()

		index = 0
		for user in users:
			if index == self.user_list.rowCount():
				self.user_list.insertRow(index)
			name_item = QTableWidgetItem(user.name)
			name_item.setFlags(name_item.flags() & ~Qt.ItemIsEditable)
			self.user_list.setItem(index, 0, name_item)
			id_item = QTableWidgetItem(str(user.id))
			id_item.setFlags(id_item.flags() & ~Qt.ItemIsEditable)
			self.user_list.setItem(index, 1, id_item)
			record_item = QTableWidgetItem(user.record_str())
			record_item.setFlags(record_item.flags() & ~Qt.ItemIsEditable)
			self.user_list.setItem(index, 2, record_item)
			index += 1
		self.user_list.show()

	def sort_by_name(self):
		self.sort_order = 'by_name'
		self.update()

	def sort_by_rank(self):
		self.sort_order = 'by_rank'
		self.update()

	def player_added(self, player, user):
		self.update()

	def player_removed(self, player):
		self.update()

	def report_result(self, player, record, win_or_draw):
		pass

#.........这里部分代码省略.........
开发者ID:zlohner,项目名称:TournamentOrganizer,代码行数:103,代码来源:user_manager_widget.py

示例13: Table

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]
class Table(QWidget):


    def __init__(self):
        super().__init__()

        self.lay = QHBoxLayout(self)
        self.tableWidget = QTableWidget(self)

        self.lay.addWidget(self.tableWidget)

        for i in range(2):
            self.tableWidget.insertRow(i)
            self.tableWidget.insertColumn(i)

        for i in range(2):
            for j in range(2):
                self.tableWidget.setItem(i, j, QTableWidgetItem(''))

        # self.tableWidget.setItem(int row, int column, QTableWidgetItem *item)
        # self.tableWidget.takeItem(int row, int column)

        self.load()

    def load(self):
        if os.path.exists('temp.xls'):
            # открываем файл
            rb = xlrd.open_workbook('temp.xls', formatting_info=True)

            # выбираем активный лист
            sheet = rb.sheet_by_index(0)

            # получаем список значений из всех записей
            # vals = [sheet.row_values(rownum) for rownum in range(sheet.nrows)]

            rows = self.tableWidget.rowCount()
            cols = self.tableWidget.columnCount()

            print(':', rows, cols)

            for rownum in range(rows):
                row = sheet.row_values(rownum)
                for col in range(cols):
                    print(rownum, col)
                    item = self.tableWidget.item(rownum, col)
                    item.setText(row[col])

    def save(self):
        wb = xlwt.Workbook()
        ws = wb.add_sheet('Test')

        rows = self.tableWidget.rowCount()
        cols = self.tableWidget.columnCount()

        for row in range(rows):
            for col in range(cols):
                item = self.tableWidget.item(row, col)
                ws.write(row, col, item.text())

        # сохраняем рабочую книгу
        wb.save('temp.xls')

    def closeEvent(self, event):
        print('saving...')
        self.save()
        return super().closeEvent(event)
开发者ID:aaveter,项目名称:curs_2016_b,代码行数:68,代码来源:table.py

示例14: PlanningCertification

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]

#.........这里部分代码省略.........

            linha+=1

        self.tableWidget.setSortingEnabled(False)

    def gerar_relatorio_planejamento(self):
        if len(self.filtro_tabela) == 0 :
            QMessageBox.about(self,'Warning','Dados insuficientes para gerar relatório!')
            return None
        if len(self.filtro_tabela) > 0 :

            # Análise do Período
            periodo = "Período de Análise:  "" De "+self.dateEdit.text()+" até "+self.dateEdit_2.text()+""
            # Análise Filtro Manutenção
            planejameto_niveis_manutencao = str()
            if self.checkBox_n1_2.isChecked(): planejameto_niveis_manutencao = " N1 "
            if self.checkBox_n2_2.isChecked(): planejameto_niveis_manutencao = " N2 "
            if self.checkBox_n3_2.isChecked(): planejameto_niveis_manutencao = " N3 "
            if self.checkBox_n1_2.isChecked() and self.checkBox_n2_2.isChecked() : planejameto_niveis_manutencao = " N1 , N2 "
            if self.checkBox_n1_2.isChecked() and self.checkBox_n3_2.isChecked() : planejameto_niveis_manutencao = " N1 , N3 "
            if self.checkBox_n2_2.isChecked() and self.checkBox_n3_2.isChecked() : planejameto_niveis_manutencao = " N2 , N3 "
            if self.checkBox_n1_2.isChecked() and self.checkBox_n2_2.isChecked() and self.checkBox_n3_2.isChecked() : planejameto_niveis_manutencao = "N1,  N2, N3 "

            # Análise Filtro Manutenção Vencidas
            planejameto_niveis_manutencao_vencida = str()
            if self.checkBox_n1_vencida.isChecked(): planejameto_niveis_manutencao_vencida = " Inclui na lista os equipamentos que estão com a manutenção N1 vencida"
            if self.checkBox_n2_vencida.isChecked(): planejameto_niveis_manutencao_vencida = " Inclui na lista os equipamentos que estão com a manutenção N2 vencida"
            if self.checkBox_n3_vencida.isChecked(): planejameto_niveis_manutencao_vencida = " Inclui na lista os equipamentos que estão com a manutenção N3 vencida"
            if self.checkBox_n1_vencida.isChecked() and self.checkBox_n2_vencida.isChecked() : planejameto_niveis_manutencao_vencida = "Inclui na lista os equipamentos que estão com a manutenção(s) N1 e N2 vencida(s)  "
            if self.checkBox_n1_vencida.isChecked() and self.checkBox_n3_vencida.isChecked() : planejameto_niveis_manutencao_vencida = "Inclui na lista os equipamentos que estão com a manutenção(s) N1 e N3 vencida(s)  "
            if self.checkBox_n2_vencida.isChecked() and self.checkBox_n3_vencida.isChecked() : planejameto_niveis_manutencao_vencida = "Inclui na lista os equipamentos que estão com a manutenção(s) N2 e N3 vencida(s)  "
            if self.checkBox_n1_vencida.isChecked() and self.checkBox_n2_vencida.isChecked() and self.checkBox_n3_vencida.isChecked() : planejameto_niveis_manutencao_vencida = "Inclui na lista os equipamentos que estão com a manutenção(s) N1, N2 e N3 vencida(s)  "
            if self.checkBox_n1_vencida.isChecked()==False and self.checkBox_n2_vencida.isChecked()==False and self.checkBox_n3_vencida.isChecked()==False : planejameto_niveis_manutencao_vencida = "Não estão incluidos os equipamentos com manutenções vencidas "


            # Montagem do Relatório
            relatorio_planejamento = Report('relatorio_planejamento.pdf')

            relatorio_planejamento.setar_primeira_pagina('Relatório de Certificação', 'Planejamento')

            relatorio_planejamento.setagem_cabecalho('Certificação - Planejamento')

            relatorio_planejamento.adicionar_topico("1 - Filtro - Previsão de Próximas Manutenções")

            relatorio_planejamento.adicionar_paragrafo(periodo)

            relatorio_planejamento.adicionar_paragrafo(" Equipamentos que irão vencer no período os níveis de manutenção "+planejameto_niveis_manutencao+"")

            relatorio_planejamento.adicionar_paragrafo(planejameto_niveis_manutencao_vencida)


            # Leitura da TableWidget da tela do programa
            index_linha = 0
            cabecalhos = ['Trace Number', 'Equip.', 'Próx. N1', 'Próx. N2', 'Próx. N3', 'DNV','Próx. TC', 'Próx. Insp. Vis', 'Próx. Recer']
            lista_tabela = list()
            lista_tabela.append(cabecalhos)
            while index_linha < self.tableWidget.rowCount():
                index_coluna = 0
                linha = list()
                while index_coluna < self.tableWidget.columnCount():
                    if self.tableWidget.item(index_linha,index_coluna) != None:
                        linha.append(self.tableWidget.item(index_linha,index_coluna).text())
                    else:
                        linha.append('-')
                    index_coluna += 1
                lista_tabela.append(linha)
                index_linha += 1


            relatorio_planejamento.adicionar_tabela(lista_tabela)
            relatorio_planejamento.criar_relatorio_pdf()

    def gerar_export_excel(self):
        # Leitura da TableWidget da tela do programa
            if self.tableWidget.rowCount()== 0:
                QMessageBox.about(self,'Warning','Tabela de dados inexistente')
                return  None
            lista_tabela = list()
            cabecalhos = list()
            index_coluna = 0
            while index_coluna < self.tableWidget.columnCount():
                cabecalhos.append(self.tableWidget.horizontalHeaderItem(index_coluna).text())
                index_coluna = index_coluna + 1
            lista_tabela.append(cabecalhos)
            index_linha = 0
            while index_linha < self.tableWidget.rowCount():
                index_coluna = 0
                linha = list()
                while index_coluna < self.tableWidget.columnCount():
                    if self.tableWidget.item(index_linha,index_coluna) != None:
                        linha.append(self.tableWidget.item(index_linha,index_coluna).text())
                    else:
                        linha.append('-')
                    index_coluna += 1
                lista_tabela.append(linha)
                index_linha += 1
            exportar = ExcelExport()
            exportar.exportacao(lista_tabela)
            QMessageBox.about(self,'Message','Arquivo exportado com sucesso')
            return None
开发者ID:losimonassi,项目名称:Searchfication,代码行数:104,代码来源:File_Planning_Certification.py

示例15: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import rowCount [as 别名]

#.........这里部分代码省略.........
            if sourceRow != -1:
                sourceItems = self.getRow(sourceRow)
                destItems = self.getRow(destRow)
                self.setRow(destRow, sourceItems)
                self.setRow(sourceRow, destItems)
                self.tableWidget.selectRow(destRow)  # 修改焦点
                log.debug(self.tableContents)
        except AttributeError:
            if self.sender().objectName() == "up":
                QMessageBox.warning(self, self.tr("Warning"), self.tr("The row is to top."))
            else:
                QMessageBox.warning(self, self.tr("Warning"), self.tr("The row is to bottom."))

    def getRow(self, rowIndex):
        """获取行"""
        rowItems = []
        for i in range(7):
            item = self.tableWidget.item(rowIndex, i)
            rowItems.append(item.text())
        rowItems.append(self.tableContents[rowIndex].get_rules(ui=True))
        return rowItems

    def setRow(self, rowIndex, rowItems):
        """设置行"""
        for n, i in enumerate(rowItems):
            if n == len(rowItems) - 1:
                self.tableContents[rowIndex].set_rules(i)
            else:
                item = self.tableWidget.item(rowIndex, n)
                item.setText(i)

    def addRowSlot(self):
        """添加行"""
        rowIndex = self.tableWidget.rowCount()
        self.tableWidget.setRowCount(rowIndex + 1)
        self.tableContents.append(Checker())
        self.updateTableSlot(0)  # 更新列表控件
        log.debug(self.tableContents)

    def delRowSlot(self):
        """删除行"""
        # 焦点默认在第一行,要设置setFocusPolicy(Qt.NoFocus)
        rowIndex = self.tableWidget.currentRow()
        if rowIndex != -1:
            self.tableWidget.removeRow(rowIndex)
            self.tableContents.remove(self.tableContents[rowIndex])
            log.debug(self.tableContents)
        else:
            QMessageBox.warning(self, self.tr("Warning"), self.tr("Please select a row."))

    def loadData(self, data):
        """载入数据"""
        self.tableContents = []  # list.clear() Python 3
        for i in data:
            self.tableContents.append(Checker(i))

    def checkUpdateSlot(self):
        """执行更新检查"""
        self.wtime[0] = int(time.time())  # 计时
        self.statusbar.showMessage(self.tr("checking..."))
        self.progressBar.setValue(0)
        self.progressBar.show()
        self.progressVal = 0
        self.taskVal = 0

        for t in range(self.workerCount):
开发者ID:FZUG,项目名称:repo-checker,代码行数:70,代码来源:gui.py


注:本文中的PyQt5.QtWidgets.QTableWidget.rowCount方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。