def __init__(self, text, icon, tooltip=None, is_read_only=False):
     QTableWidgetItem.__init__(self, text)
     if icon:
         self.setIcon(icon)
     if tooltip:
         self.setToolTip(tooltip)
     if is_read_only:
         self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
Exemplo n.º 2
0
 def __init__(self, date_read, is_read_only=False, default_to_today=False):
     if date_read == UNDEFINED_DATE and default_to_today:
         date_read = now()
     if is_read_only:
         QTableWidgetItem.__init__(self, format_date(date_read, None), QtGui.QTableWidgetItem.UserType)
         self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
     else:
         QTableWidgetItem.__init__(self, '', QtGui.QTableWidgetItem.UserType)
         self.setData(Qt.DisplayRole, QDateTime(date_read))
Exemplo n.º 3
0
    def __init__(self, date_read, is_read_only=False, default_to_today=False, fmt=None):
#        debug_print("DateTableWidgetItem:__init__ - date_read=", date_read)
        if date_read is None or date_read == UNDEFINED_DATE and default_to_today:
            date_read = now()
        if is_read_only:
            QTableWidgetItem.__init__(self, format_date(date_read, fmt), QTableWidgetItem.UserType)
            self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
            self.setData(Qt.DisplayRole, QDateTime(date_read))
        else:
            QTableWidgetItem.__init__(self, '', QTableWidgetItem.UserType)
            self.setData(Qt.DisplayRole, QDateTime(date_read))
Exemplo n.º 4
0
    def fill_in_table(self, tags, tag_to_match):
        data = self.get_book_ids(self.apply_vl_checkbox.isChecked())
        self.all_tags = {}
        for k,v,count in data:
            self.all_tags[v] = {'key': k, 'count': count, 'cur_name': v,
                                'is_deleted': k in self.to_delete}
            self.original_names[k] = v
        self.ordered_tags = sorted(self.all_tags.keys(), key=self.sorter)
        if tags is None:
            tags = self.ordered_tags

        select_item = None
        self.table.blockSignals(True)
        self.table.clear()
        self.table.setColumnCount(3)
        self.name_col = QTableWidgetItem(_('Tag'))
        self.table.setHorizontalHeaderItem(0, self.name_col)
        self.name_col.setIcon(self.up_arrow_icon)
        self.count_col = QTableWidgetItem(_('Count'))
        self.table.setHorizontalHeaderItem(1, self.count_col)
        self.count_col.setIcon(self.blank_icon)
        self.was_col = QTableWidgetItem(_('Was'))
        self.table.setHorizontalHeaderItem(2, self.was_col)
        self.count_col.setIcon(self.blank_icon)

        self.table.setRowCount(len(tags))

        for row,tag in enumerate(tags):
            item = NameTableWidgetItem()
            item.set_is_deleted(self.all_tags[tag]['is_deleted'])
            _id = self.all_tags[tag]['key']
            item.setData(Qt.UserRole, _id)
            item.set_initial_text(tag)
            if _id in self.to_rename:
                item.setText(self.to_rename[_id])
            else:
                item.setText(tag)
            item.setFlags(item.flags() | Qt.ItemIsSelectable | Qt.ItemIsEditable)
            self.table.setItem(row, 0, item)
            if tag == tag_to_match:
                select_item = item

            item = CountTableWidgetItem(self.all_tags[tag]['count'])
            # only the name column can be selected
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            self.table.setItem(row, 1, item)

            item = QTableWidgetItem()
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            if _id in self.to_rename or _id in self.to_delete:
                item.setData(Qt.DisplayRole, tag)
            self.table.setItem(row, 2, item)
        self.table.blockSignals(False)
        return select_item
Exemplo n.º 5
0
 def addGroupe (self,groupe_name,type_alert):
     item_name =QTableWidgetItem(groupe_name)
     item_type =QTableWidgetItem(type_alert)
     if item_type == "delete":
         item_name.setBackground(QBrush("red"))
         item_type.setBackground(QBrush("red"))
     elif item_type == "new":
         item_name.setBackground(QBrush("green"))
         item_type.setBackground(QBrush("green"))    
     self.list_modified_groupes.insertRow(0)
     self.list_modified_groupes.setItem(0,0,item_name)
     self.list_modified_groupes.setItem(0,1,item_type)
Exemplo n.º 6
0
 def __init__(self, checked=False, is_tristate=False):
     QTableWidgetItem.__init__(self, '')
     self.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled ))
     if is_tristate:
         self.setFlags(self.flags() | Qt.ItemIsTristate)
     if checked:
         self.setCheckState(Qt.Checked)
     else:
         if is_tristate and checked is None:
             self.setCheckState(Qt.PartiallyChecked)
         else:
             self.setCheckState(Qt.Unchecked)
Exemplo n.º 7
0
 def update_table(self, init=False):
     if init:
         self.init_table()
     records = DatabaseManager.get_all_keyboards()
     self.keyboard_table.setRowCount(records[0])
     for idx, record in enumerate(records[1]):
         self.keyboard_table.setItem(idx, 1, QTableWidgetItem(record.language_name))
         self.keyboard_table.setItem(idx, 2, QTableWidgetItem(str(record.id)))
         chk_box = QTableWidgetItem()
         chk_box.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
         chk_box.setCheckState(Qt.Unchecked)
         self.keyboard_table.setItem(idx, 0, chk_box)
     self.keyboard_table.resizeRowsToContents()
     return
Exemplo n.º 8
0
    def __init__(self, parent, get_option, get_help, db=None, book_id=None):
        # Dummy attributes to fool the Widget() option handler code. We handle
        # everything in our *handler methods.
        for i in range(1, 4):
            x = 'sr%d_'%i
            for y in ('search', 'replace'):
                z = x + y
                setattr(self, 'opt_'+z, z)
        self.opt_search_replace = 'search_replace'

        Widget.__init__(self, parent,
                ['search_replace',
                 'sr1_search', 'sr1_replace',
                 'sr2_search', 'sr2_replace',
                 'sr3_search', 'sr3_replace']
                )
        self.db, self.book_id = db, book_id

        self.sr_search.set_msg(_('&Search Regular Expression'))
        self.sr_search.set_book_id(book_id)
        self.sr_search.set_db(db)

        self.sr_search.doc_update.connect(self.update_doc)

        proto = QTableWidgetItem()
        proto.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable + Qt.ItemIsEnabled))
        self.search_replace.setItemPrototype(proto)
        self.search_replace.setColumnCount(2)
        self.search_replace.setColumnWidth(0, 320)
        self.search_replace.setColumnWidth(1, 320)
        self.search_replace.setHorizontalHeaderLabels([
            _('Search Regular Expression'), _('Replacement Text')])

        self.sr_add.clicked.connect(self.sr_add_clicked)
        self.sr_change.clicked.connect(self.sr_change_clicked)
        self.sr_remove.clicked.connect(self.sr_remove_clicked)
        self.sr_load.clicked.connect(self.sr_load_clicked)
        self.sr_save.clicked.connect(self.sr_save_clicked)
        self.sr_up.clicked.connect(self.sr_up_clicked)
        self.sr_down.clicked.connect(self.sr_down_clicked)
        self.search_replace.currentCellChanged.connect(self.sr_currentCellChanged)

        self.initialize_options(get_option, get_help, db, book_id)

        try:
            self.rh_label.setText(self.rh_label.text() % localize_user_manual_link(
                'https://manual.calibre-ebook.com/regexp.html'))
        except TypeError:
            pass  # link already localized
Exemplo n.º 9
0
 def data(self, role):
     if role == Qt.DisplayRole:
         return self.current_value
     elif role == Qt.EditRole:
         return self.current_value
     else:
         return QTableWidgetItem.data(self, role)
Exemplo n.º 10
0
def mostrar_table_widget():
    ui_ventana_table_widget.setupUi(MainWindow)
    #vamos a rellenar la tabla
    libros = operaciones_bd.obtener_libros()
    fila = 0
    for l in libros:
        ui_ventana_table_widget.tabla_libros.insertRow(fila)  #creo la fila
        #celda para el id
        celda = QTableWidgetItem(str(l[0]))  #creo la celda
        ui_ventana_table_widget.tabla_libros.setItem(fila, 0, celda)
        #celda para el nombre
        celda = QTableWidgetItem(str(l[1]))
        ui_ventana_table_widget.tabla_libros.setItem(fila, 1, celda)
        #celda para las paginas
        celda = QTableWidgetItem(str(l[2]))
        ui_ventana_table_widget.tabla_libros.setItem(fila, 2, celda)
        #celda para el precio
        celda = QTableWidgetItem(str(l[3]))
        ui_ventana_table_widget.tabla_libros.setItem(fila, 3, celda)

        fila += 1
Exemplo n.º 11
0
 def add_columns_to_widget(self):
     '''
     Get the list of columns from the preferences. Clear the current table
     and add the current column set
     '''
     self.column_order = [x[0] for x in get_qv_field_list(self.fm) if x[1]]
     self.books_table.clear()
     self.books_table.setRowCount(0)
     self.books_table.setColumnCount(len(self.column_order))
     for idx, col in enumerate(self.column_order):
         t = QTableWidgetItem(self.fm[col]['name'])
         self.books_table.setHorizontalHeaderItem(idx, t)
Exemplo n.º 12
0
 def bd_score(self):
     con = sqlite3.connect(resource_path("DB/score.db"))
     # Создание курсора
     cur = con.cursor()
     # Выполнение запроса и получение всех результатов
     result = cur.execute(
         "SELECT * FROM main ORDER BY score DESC;").fetchmany(5)
     cur.execute("DROP TABLE main")
     cur.execute("CREATE TABLE main (name STRING, score INTEGER)")
     for item in result:
         cur.execute("INSERT INTO main VALUES(?, ?)", (item[0], item[1]))
         con.commit()
     # Вывод результатов на экран
     if result != []:
         self.table_score.setColumnCount(len(result[0]))
         self.table_score.setRowCount(0)
         for i, row in enumerate(result):
             self.table_score.setRowCount(self.table_score.rowCount() + 1)
             for j, elem in enumerate(row):
                 item = QTableWidgetItem(str(elem))
                 self.table_score.setItem(i, j, item)
                 item.setFlags(QtCore.Qt.ItemIsEnabled)
         self.table_score.setHorizontalHeaderItem(
             0, QTableWidgetItem("Имя игрока"))
         self.table_score.setHorizontalHeaderItem(1,
                                                  QTableWidgetItem("Счет"))
         self.table_score.setColumnWidth(0, 127)
         self.table_score.setColumnWidth(1, 20)
     con.close()
Exemplo n.º 13
0
 def update_table(self, init=False):
     if init:
         self.init_table()
     records = DatabaseManager.get_all_keyboards()
     self.keyboard_table.setRowCount(records[0])
     for idx, record in enumerate(records[1]):
         self.keyboard_table.setItem(idx, 1, QTableWidgetItem(record.language_name))
         self.keyboard_table.setItem(idx, 2, QTableWidgetItem(str(record.id)))
         chk_box = QTableWidgetItem()
         chk_box.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
         chk_box.setCheckState(Qt.Unchecked)
         self.keyboard_table.setItem(idx, 0, chk_box)
     self.keyboard_table.resizeRowsToContents()
     return
Exemplo n.º 14
0
    def populate_table_row(self, row, line):

        href = line['href']
        if line['anchor']:
            href = "%s#%s" % (href, line['anchor'])

        href_cell = ReadOnlyTableWidgetItem(href)
        href_cell.setToolTip(line['sample'] + SAMPLE_NOTE)
        href_cell.setData(Qt.UserRole, line['num'])
        self.setItem(row, 0, href_cell)

        if 'guide' in line:
            guide = "(%s):%s" % line['guide']
        else:
            guide = ""
        guide_cell = ReadOnlyTableWidgetItem(guide)
        guide_cell.setToolTip(
            _("Indicates 'special' pages: copyright, titlepage, etc."))
        self.setItem(row, 1, guide_cell)

        toc_str = "|".join(line['toc'])
        toc_cell = QTableWidgetItem(toc_str)
        toc_cell.setData(Qt.UserRole, toc_str)
        toc_cell.setToolTip(
            _('''Click and copy hotkey to copy text.
Double-click to edit ToC entry.
Pipes(|) divide different ToC entries to the same place.'''))
        self.setItem(row, 2, toc_cell)
Exemplo n.º 15
0
    def fill_in_table(self, tags, tag_to_match):
        select_item = None
        self.table.blockSignals(True)
        self.table.clear()
        self.table.setColumnCount(3)
        self.name_col = QTableWidgetItem(_('Tag'))
        self.table.setHorizontalHeaderItem(0, self.name_col)
        self.name_col.setIcon(self.up_arrow_icon)
        self.count_col = QTableWidgetItem(_('Count'))
        self.table.setHorizontalHeaderItem(1, self.count_col)
        self.count_col.setIcon(self.blank_icon)
        self.was_col = QTableWidgetItem(_('Was'))
        self.table.setHorizontalHeaderItem(2, self.was_col)
        self.count_col.setIcon(self.blank_icon)

        self.table.setRowCount(len(tags))

        for row,tag in enumerate(tags):
            item = NameTableWidgetItem()
            item.set_is_deleted(self.all_tags[tag]['is_deleted'])
            item.setText(self.all_tags[tag]['cur_name'])
            item.set_initial_text(tag)
            item.setData(Qt.UserRole, self.all_tags[tag]['key'])
            item.setFlags(item.flags() | Qt.ItemIsSelectable | Qt.ItemIsEditable)
            self.table.setItem(row, 0, item)
            if tag == tag_to_match:
                select_item = item

            item = CountTableWidgetItem(self.all_tags[tag]['count'])
            # only the name column can be selected
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            self.table.setItem(row, 1, item)

            item = QTableWidgetItem()
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            if tag != self.all_tags[tag]['cur_name'] or self.all_tags[tag]['is_deleted']:
                item.setData(Qt.DisplayRole, tag)
            self.table.setItem(row, 2, item)
        self.table.blockSignals(False)
        return select_item
Exemplo n.º 16
0
def mostrar_table_widget():
    ui_ventana_table_widget.setupUi(MainWindow)
    #vamos a rellenar la tabla:
    libros = operaciones_bd.obtener_libros()
    fila = 0
    for l in libros:
        ui_ventana_table_widget.tabla_libros.insertRow(fila)
        #y ahora meto las celdas correspondientes en la fila
        columna_indice = 0
        for valor in l:

            if columna_indice == 4:
                if valor == 0:
                    valor = "NO"
                else:
                    valor = "SI"

            celda = QTableWidgetItem(str(valor))
            ui_ventana_table_widget.tabla_libros.setItem(
                fila, columna_indice, celda)
            columna_indice += 1
        #despues de rellenar los datos en la fila
        #boton ver detalles:
        boton_ver_detalles = QPushButton("ver detalles")
        boton_ver_detalles.clicked.connect(partial(cargar_ver_detalles, l[0]))
        ui_ventana_table_widget.tabla_libros.setCellWidget(
            fila, 3, boton_ver_detalles)

        #voy a meterle un boton de borrar
        boton_borrar = QPushButton("borrar")
        boton_borrar.clicked.connect(partial(borrar_libro, l[0]))
        ui_ventana_table_widget.tabla_libros.setCellWidget(
            fila, 4, boton_borrar)

        boton_editar = QPushButton("editar")
        boton_editar.clicked.connect(partial(editar_libro, l[0], l[1]))
        ui_ventana_table_widget.tabla_libros.setCellWidget(
            fila, 5, boton_editar)

        #muestro una miniatura:
        label_miniatura = QLabel()
        ruta_imagen = "imagenes/" + str(l[0]) + ".jpg"
        objeto_path = Path(ruta_imagen)
        existe = objeto_path.is_file()
        if existe == True:  #Path("imagenes/" + l[0] + ".jpg").is_file() :
            pixmap = QPixmap(ruta_imagen)
            pixmap_redim = pixmap.scaledToHeight(40)
            label_miniatura.setPixmap(pixmap_redim)
            ui_ventana_table_widget.tabla_libros.setCellWidget(
                fila, 6, label_miniatura)

        fila += 1
Exemplo n.º 17
0
 def s_select_all_data(self):     
     self.s_delete_all_records()        
     font = QtGui.QFont()
     font.setPointSize(12)
     self.tableWidget.setFont(font) 
     self.tableWidget.horizontalHeader().setStretchLastSection(True)
   
     self.tableWidget.setHorizontalHeaderLabels(['User Id.', ' First Name ', 'Last Name','Role','LoginId','Phone','Email Id','Password'])
     print("role :"+str(self.login_user_role))
    
     connection = sqlite3.connect("fci.db")
     if(str(self.login_user_role) ==  'SUPER_ADMIN'):
             results=connection.execute("select USER_ID,FIRST_NAME,LAST_NAME,ROLE,LOGIN_ID,PHONE_NO,EMAIL_ID,PWD from USERS_MST where ROLE != 'SUPER_ADMIN'")
             self.comboBox.setEnabled(True)
             self.pushButton_2.setDisabled(True) #delete           
             self.pushButton_6.setEnabled(True) #reset
             #self.pushButton_4.setEnabled(True) #add
     elif(str(self.login_user_role) ==  'ADMIN'):
             self.comboBox.clear()
             self.comboBox.addItem("")
             self.comboBox.setItemText(0, "OPERATOR")
             self.comboBox.addItem("")
             self.comboBox.setItemText(1, "SUPERVISOR")                
         
             results=connection.execute("select USER_ID,FIRST_NAME,LAST_NAME,ROLE,LOGIN_ID,PHONE_NO,EMAIL_ID,PWD from USERS_MST WHERE USER_ID IN (SELECT USER_ID FROM ADMINS_USER_IDS_VW)")
     elif(str(self.login_user_role) ==  'SUPERVISOR'):
             self.comboBox.clear()
             self.comboBox.addItem("")
             self.comboBox.setItemText(0, "OPERATOR")
            
             
             
             results=connection.execute("select USER_ID,FIRST_NAME,LAST_NAME,ROLE,LOGIN_ID,PHONE_NO,EMAIL_ID,PWD from USERS_MST WHERE USER_ID IN (SELECT USER_ID FROM SUPERVISORS_USER_IDS_VW)")
     else:
             results=connection.execute("select USER_ID,FIRST_NAME,LAST_NAME,ROLE,LOGIN_ID,PHONE_NO,EMAIL_ID,PWD from USERS_MST WHERE USER_ID='"+str(self.login_user_id)+"'")
             self.comboBox.setDisabled(True)
             self.pushButton_2.setDisabled(True) #delete           
             self.pushButton_6.setDisabled(True) #reset
             self.pushButton_4.setDisabled(True) #add
     
     
     
     
     for row_number, row_data in enumerate(results):            
         self.tableWidget.insertRow(row_number)
         for column_number, data in enumerate(row_data):
             self.tableWidget.setItem(row_number,column_number,QTableWidgetItem(str (data)))                
     connection.close()   
     #self.tableWidget.resizeColumnsToContents()
     self.tableWidget.resizeRowsToContents()
     self.tableWidget.horizontalHeader().setStretchLastSection(True)
     self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
Exemplo n.º 18
0
    def update_players(self):
        for i in range(0, self.tableWidget.rowCount()):
            self.tableWidget.removeRow(i)
        self.tableWidget.setRowCount(len(self.server.get_players()))

        row = 0
        column = 0
        for player in self.server.get_players():
            for item in player.values():
                self.tableWidget.setItem(row, column, QTableWidgetItem(str(item)))
                column += 1
            row += 1
            column = 0
Exemplo n.º 19
0
    def __init__(self, parent, items):
        QDialog.__init__(self, parent)
        Ui_DeleteMatchingFromDeviceDialog.__init__(self)
        self.setupUi(self)

        self.explanation.setText('<p>' +
                                 _('All checked books will be '
                                   '<b>permanently deleted</b> from your '
                                   'device. Please verify the list.') + '</p>')
        self.buttonBox.accepted.connect(self.accepted)
        self.buttonBox.rejected.connect(self.rejected)
        self.table.cellClicked.connect(self.cell_clicked)
        self.table.setSelectionMode(QAbstractItemView.NoSelection)
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels([
            '',
            _('Location'),
            _('Title'),
            _('Author'),
            _('Date'),
            _('Format'),
            _('Path')
        ])
        rows = 0
        for card in items:
            rows += len(items[card][1])
        self.table.setRowCount(rows)
        row = 0
        for card in items:
            (model, books) = items[card]
            for (id, book) in books:
                item = QTableWidgetItem()
                item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                item.setCheckState(Qt.Checked)
                item.setData(Qt.UserRole, (model, id, book.path))
                self.table.setItem(row, 0, item)
                self.table.setItem(row, 1, tableItem(card))
                self.table.setItem(row, 2, titleTableItem(book.title))
                self.table.setItem(row, 3, authorTableItem(book))
                self.table.setItem(row, 4, dateTableItem(book.datetime))
                self.table.setItem(
                    row, 5, centeredTableItem(book.path.rpartition('.')[2]))
                self.table.setItem(row, 6, tableItem(book.path))
                row += 1
        self.table.setCurrentCell(0, 1)
        self.table.resizeColumnsToContents()
        self.table.setSortingEnabled(True)
        self.table.sortByColumn(2, Qt.AscendingOrder)
        self.table.setCurrentCell(0, 1)
Exemplo n.º 20
0
 def credentials_update(self):
     try:
         vault = open(encryption_engine.who_is(self.current_user), "r")
     except :
         vault = open(encryption_engine.who_is(self.current_user), "w")
     self.info = encryption_engine.get_user_cred(self.current_user)
     self.row_len = len(self.info)
     self.ui_siu.tableWidget.setRowCount(self.row_len)
     for i in range(self.row_len):
         for j in range(2):
             item  = QTableWidgetItem("  " + self.info[i][j])
             self.ui_siu.tableWidget.setItem(i,j,item)
     vault.close()
Exemplo n.º 21
0
 def edit_rule(self, r=-1):
     key = name = template = ''
     if r > -1:
         key, name, template = map(lambda c: self.table.item(r, c).text(), range(3))
     d = IdLinksRuleEdit(key, name, template, self)
     if d.exec_() == d.Accepted:
         if r < 0:
             self.table.setRowCount(self.table.rowCount() + 1)
             r = self.table.rowCount() - 1
         rule = d.rule
         for c in range(3):
             self.table.setItem(r, c, QTableWidgetItem(rule[c]))
         self.table.scrollToItem(self.table.item(r, 0))
Exemplo n.º 22
0
    def select_all_data(self):
        self.whr_sql = ""
        self.delete_all_records()
        font = QtGui.QFont()
        font.setPointSize(10)
        self.tableWidget.setFont(font)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setColumnWidth(0, 150)
        self.tableWidget.setColumnWidth(1, 150)
        self.tableWidget.setColumnWidth(2, 150)
        self.tableWidget.setColumnWidth(3, 150)
        self.tableWidget.setColumnWidth(4, 150)
        self.tableWidget.setColumnWidth(5, 200)
        self.tableWidget.setColumnWidth(6, 200)
        self.tableWidget.setColumnWidth(7, 50)

        if (self.radioButton_3.isChecked()):
            self.whr_sql = " WHERE strftime('%Y-%m-%d',START_DATE)  between '" + str(
                self.from_date) + "' and '" + str(self.to_date) + "' limit 400"
        elif (self.radioButton_4.isChecked()):
            self.whr_sql = "WHERE ISSUE_ID = '" + self.comboBox.currentText(
            ) + "'"
        else:
            self.whr_sql = "Order by ISSUE_ID DESC"

        self.tableWidget.setHorizontalHeaderLabels([
            'Order ID.', ' Total Trucks ', 'Total Net.Wt Ton',
            'Total Accpt.Bags.Cnt', 'Status', 'Release Date', 'Release Time',
            'Started On'
        ])

        connection = sqlite3.connect("fci.db")
        print(
            "SELECT (SELECT A.ORDER_ID FROM ISSUE_MST A WHERE A.ISSUE_ID=ISSUE_ID ) as ISSUE_ID,TOTAL_TRUCKS,printf(\"%.3f\", TOTAL_NET_WT),printf(\"%3d\", TOTAL_ACCEPTED_BAGS),STATUS,RELEASE_DATE,RELEASE_TIME,START_DATE FROM ISSUE_LIST_VW "
            + str(self.whr_sql))

        results = connection.execute(
            "SELECT (SELECT A.ORDER_ID FROM ISSUE_MST A WHERE A.ISSUE_ID=ISSUE_ID ) as ISSUE_ID,TOTAL_TRUCKS,printf(\"%.3f\", TOTAL_NET_WT),printf(\"%3d\", TOTAL_ACCEPTED_BAGS),STATUS,RELEASE_DATE,RELEASE_TIME,START_DATE FROM ISSUE_LIST_VW "
            + str(self.whr_sql))
        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number,
                                         QTableWidgetItem(str(data)))
                #self.lineEdit.setText("")
        connection.close()
        #self.tableWidget.resizeColumnsToContents()
        #self.tableWidget.resizeRowsToContents()
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
        self.update_report_param()
Exemplo n.º 23
0
 def ins_button_clicked(self):
     row = self.table.currentRow()
     if row < 0:
         error_dialog(self,
                      _('Select a cell'),
                      _('Select a cell before clicking the button'),
                      show=True)
         return
     self.table.insertRow(row)
     self.table.setItem(row, 0, QTableWidgetItem())
     c = QComboBox(self)
     c.addItem('')
     c.addItems(QColor.colorNames())
     self.table.setCellWidget(row, 1, c)
Exemplo n.º 24
0
 def makeModel(self, tbView, mtxIn):
     tbView.setRowCount(len(mtxIn))
     tbView.setColumnCount(len(mtxIn[0]))
     for i, row in enumerate(mtxIn):
         for j, val in enumerate(row):
             if type(val) == QDate:
                 val = val.toPyDate().isoformat()
             elif type(val) == QTime:
                 val = val.toPyTime().isoformat()
             elif type(val) == g.Blob:
                 val = val.name
             item = QTableWidgetItem(str(val))
             tbView.setItem(i, j, item)
     self.setMainTableHeader(self, tbView)
Exemplo n.º 25
0
 def llenarTablaVar(self):
     self.tablaVariables.clear()
     self.tablaVariables.setRowCount(1)
     self.tablaVariables.setColumnCount(self.numVariables)
     for i in range(self.numVariables):
         item1 = QTableWidgetItem(f"X{i+1}")
         item1.setBackground(QtGui.QColor(37, 40, 80))
         item1.setForeground(QtGui.QColor(255, 255, 255))
         self.tablaVariables.setHorizontalHeaderItem(i, item1)
Exemplo n.º 26
0
    def init_columns(self, defaults=False):
        # Set up columns
        self.opt_columns.blockSignals(True)
        self.model = model = self.gui.library_view.model()
        colmap = list(model.column_map)
        state = self.columns_state(defaults)
        self.hidden_cols = state['hidden_columns']
        positions = state['column_positions']
        colmap.sort(cmp=lambda x, y: cmp(positions[x], positions[y]))
        self.opt_columns.clear()

        db = model.db
        self.field_metadata = db.field_metadata

        self.opt_columns.setColumnCount(4)
        item = QTableWidgetItem(_('Column Header'))
        self.opt_columns.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem(_('Lookup name'))
        self.opt_columns.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem(_('Type'))
        self.opt_columns.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem(_('Description'))
        self.opt_columns.setHorizontalHeaderItem(3, item)

        self.opt_columns.setRowCount(len(colmap))
        self.column_desc = dict(
            map(
                lambda x: (CreateCustomColumn.column_types[x]['datatype'],
                           CreateCustomColumn.column_types[x]['text']),
                CreateCustomColumn.column_types))

        for row, col in enumerate(colmap):
            self.setup_row(self.field_metadata, row, col)

        self.restore_geometry()
        self.opt_columns.cellDoubleClicked.connect(self.row_double_clicked)
        self.opt_columns.blockSignals(False)
Exemplo n.º 27
0
    def select_all_data(self):
        self.delete_all_records()
        font = QtGui.QFont()
        font.setPointSize(10)
        self.tableWidget.setFont(font)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setColumnWidth(0, 100)
        self.tableWidget.setColumnWidth(1, 100)
        self.tableWidget.setColumnWidth(2, 100)
        self.tableWidget.setColumnWidth(3, 150)
        self.tableWidget.setColumnWidth(4, 150)
        self.tableWidget.setColumnWidth(5, 150)
        self.tableWidget.setColumnWidth(6, 150)
        self.tableWidget.setColumnWidth(7, 150)
        self.tableWidget.setColumnWidth(8, 150)
        self.tableWidget.setColumnWidth(9, 150)
        self.tableWidget.setColumnWidth(10, 150)
        self.tableWidget.setColumnWidth(11, 150)
        self.tableWidget.setColumnWidth(12, 150)
        self.tableWidget.setColumnWidth(13, 150)

        self.tableWidget.setHorizontalHeaderLabels([
            'Slip No.', 'Weighing Type', 'Vehicle No.', 'First Weight Type',
            'First Weight', 'First Weight On', 'Second Weight Type',
            'Second Weight', 'Second Weight On', 'Material', 'Net.Wt',
            'Recipt Id', 'Issue Id', 'Party Name'
        ])

        connection = sqlite3.connect("fci.db")
        if (self.status == "PENDING"):
            results = connection.execute(
                "select SERIAL_ID,CASE WHEN BATCH_ISSUE_FLG='BATCH' THEN 'RECIPT' ELSE BATCH_ISSUE_FLG END AS FLG  ,VEHICLE_NO,FIRST_WEIGHT_MODE,printf(\"%6d\", IFNULL(FIRST_WEIGHT_VAL,0)) ,FIRST_WT_CRTEATED_ON,SECOND_WT_MODE,printf(\"%6d\", IFNULL(SECOND_WT_VAL,0)) ,SECOND_WT_CREATED_ON,MATERIAL_NAME,printf(\"%6d\", IFNULL(NET_WEIGHT_VAL,0)),BATCH_ID,ISSUE_ID,PARTY_NAME FROM WEIGHT_MST WHERE  STATUS='FIRST' and FIRST_WT_CRTEATED_ON between '"
                + str(self.from_dt) + "' and '" + str(self.to_dt) + "'")
        else:
            results = connection.execute(
                "select SERIAL_ID,CASE WHEN BATCH_ISSUE_FLG='BATCH' THEN 'RECIPT' ELSE BATCH_ISSUE_FLG END AS FLG,VEHICLE_NO,FIRST_WEIGHT_MODE,printf(\"%6d\", IFNULL(FIRST_WEIGHT_VAL,0)) ,FIRST_WT_CRTEATED_ON,SECOND_WT_MODE,printf(\"%6d\", IFNULL(SECOND_WT_VAL,0)) ,SECOND_WT_CREATED_ON,MATERIAL_NAME,printf(\"%6d\", IFNULL(NET_WEIGHT_VAL,0)),BATCH_ID,ISSUE_ID,PARTY_NAME FROM WEIGHT_MST WHERE  STATUS='SECOND' and FIRST_WT_CRTEATED_ON between '"
                + str(self.from_dt) + "' and '" + str(self.to_dt) + "'")

        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number,
                                         QTableWidgetItem(str(data)))
                #self.lineEdit.setText("")
        connection.close()
        #self.tableWidget.resizeColumnsToContents()
        self.tableWidget.resizeRowsToContents()
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
Exemplo n.º 28
0
def mostrar_table_widget():
    ui_ventana_table_widget.setupUi(MainWindow)

    accesorios = operaciones_bd.obtener_accesorios()
    fila = 0
    for l in accesorios:
        ui_ventana_table_widget.tabla_accesorios.insertRow(fila)

        columna_indice = 0
        for valor in l:

            if columna_indice == 6:
                if valor == 0:
                    valor = "NO"
                else:
                    valor = "SI"

            celda = QTableWidgetItem(str(valor))
            ui_ventana_table_widget.tabla_accesorios.setItem(
                fila, columna_indice, celda)
            columna_indice += 1

        boton_ver_detalles = QPushButton("ver detalles")
        boton_ver_detalles.clicked.connect(partial(cargar_ver_detalles, l[0]))
        ui_ventana_table_widget.tabla_accesorios.setCellWidget(
            fila, 4, boton_ver_detalles)

        boton_borrar = QPushButton("borrar")
        boton_borrar.clicked.connect(partial(borrar_accesorio, l[0]))
        ui_ventana_table_widget.tabla_accesorios.setCellWidget(
            fila, 5, boton_borrar)

        boton_editar = QPushButton("editar")
        boton_editar.clicked.connect(partial(editar_accesorio, l[0], l[1]))
        ui_ventana_table_widget.tabla_accesorios.setCellWidget(
            fila, 6, boton_editar)

        label_miniatura = QLabel()
        ruta_imagen = "imagenes/" + str(l[0]) + ".jpg"
        objeto_path = Path(ruta_imagen)
        existe = objeto_path.is_file()
        if existe == True:  #Path("imagenes/" + l[0] + ".jpg").is_file() :
            pixmap = QPixmap(ruta_imagen)
            pixmap_redim = pixmap.scaledToHeight(40)
            label_miniatura.setPixmap(pixmap_redim)
            ui_ventana_table_widget.tabla_accesorios.setCellWidget(
                fila, 7, label_miniatura)

        fila += 1
Exemplo n.º 29
0
    def RR_Test(self):
        process_list = self.create_list()
        self.test = self.p.Progress(process_list)
        time_block = 3
        # time_block = int(self.time_value.text())
        r_list, avg_time, avg_w_time = self.test.RR(time_block)
        for i in range(0, len(r_list)):
            # 进程名
            name = '{}'.format(r_list[i].name)
            n_data = QTableWidgetItem(str(name))
            self.result_table.setItem(i, 0, n_data)
            # 到达时间
            arrival_time = '{}'.format('%.2f' % r_list[i].arrival_time)
            a_data = QTableWidgetItem(str(arrival_time))
            self.result_table.setItem(i, 1, a_data)
            # 服务时间
            service_time = '{}'.format('%.2f' % r_list[i].service_time)
            s_data = QTableWidgetItem(str(service_time))
            self.result_table.setItem(i, 2, s_data)
            # 优先级
            priority = '{}'.format('%.2f' % r_list[i].priority)
            p_data = QTableWidgetItem(str(priority))
            self.result_table.setItem(i, 3, p_data)
            # 开始时间
            start_time = '{}'.format('%.2f' % r_list[i].start_time)
            start_data = QTableWidgetItem(str(start_time))
            self.result_table.setItem(i, 4, start_data)
            # 结束时间
            finish_time = '{}'.format('%.2f' % r_list[i].finish_time)
            f_data = QTableWidgetItem(str(finish_time))
            self.result_table.setItem(i, 5, f_data)
            # 周转时间
            turnover_time = '{}'.format('%.2f' % r_list[i].turnover_time)
            t_data = QTableWidgetItem(str(turnover_time))
            self.result_table.setItem(i, 6, t_data)
            # 带权周转时间
            weight_time = '{}'.format('%.2f' % r_list[i].weight_time)
            w_data = QTableWidgetItem(str(weight_time))
            self.result_table.setItem(i, 7, w_data)

        s_avg_time = "{}".format('%.2f' % avg_time)
        s_avg_w_time = "{}".format('%.2f' % avg_w_time)
        self.avg_value.setText(s_avg_time)
        self.avg_w_value.setText(s_avg_w_time)
        s_time = "{}".format('%.2f' % time_block)
        self.time_value.setText(s_time)
    def addRecordsTable(self):
        """ Add Records to the Table Widget"""
        try:

            for x, fieldName in enumerate([
                    shapeField[0]
                    for shapeField in self.planHeatDMM.data.originShapeFields
            ]):

                addUserFieldCheckBox = QtWidgets.QCheckBox()
                addUserFieldCheckBox.setChecked(False)
                addUserFieldCheckBox.setObjectName(str(x))

                cell_widget = QWidget()

                lay_out = QtWidgets.QHBoxLayout(cell_widget)
                lay_out.addWidget(addUserFieldCheckBox)
                lay_out.setAlignment(Qt.AlignCenter)
                lay_out.setContentsMargins(0, 0, 0, 0)
                cell_widget.setLayout(lay_out)

                #cell_widget.mousePressEvent=self.presiona
                for data in self.planHeatDMM.data.userFieldShapeMap:
                    if data.key == fieldName:
                        addUserFieldCheckBox.setChecked(True)

                rowPosition = self.shapeFieldTable.rowCount()
                self.shapeFieldTable.insertRow(rowPosition)
                self.shapeFieldTable.setCellWidget(rowPosition, 0, cell_widget)
                self.shapeFieldTable.setItem(rowPosition, 1,
                                             QTableWidgetItem(fieldName))

                for data in self.shpDMMFieldsMapTemp:
                    if fieldName == data.user_definition_field and data.calculateModel in (
                            self.planHeatDMM.data.calculateMethod, "Both"):
                        self.shapeFieldTable.item(rowPosition,
                                                  1).setForeground(
                                                      QtGui.QColor(0, 0, 240))

        except:
            self.planHeatDMM.resources.log.write_log(
                "ERROR",
                "UserFieldShapeDialog - addRecordTable Unexpected error:" +
                str(sys.exc_info()[0]) + " " + str(sys.exc_info()[1]))
            showErrordialog(
                self.planHeatDMM.dlg,
                "UserFieldShapeDialog - addRecordTable Unexpected error:",
                str(sys.exc_info()[0]) + " " + str(sys.exc_info()[1]))
Exemplo n.º 31
0
    def setContent(self, astroTable):

        self.tableWidget.setRowCount(len(astroTable))
        self.tableWidget.setColumnCount(len(astroTable.colnames))
        self.tableWidget.setHorizontalHeaderLabels(astroTable.colnames)

        rowIdx = 0
        colIdx = 0
        for row in astroTable:
            for header in astroTable.colnames:
                self.tableWidget.setItem(
                    rowIdx, colIdx,
                    QTableWidgetItem(str(astroTable[rowIdx][header])))
                colIdx = colIdx + 1
            rowIdx = rowIdx + 1
            colIdx = 0
    def select_all_data(self):

        self.delete_all_records()
        font = QtGui.QFont()
        font.setPointSize(10)
        self.tableWidget.setFont(font)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setColumnWidth(0, 100)
        self.tableWidget.setColumnWidth(1, 100)
        self.tableWidget.setColumnWidth(2, 200)
        self.tableWidget.setColumnWidth(3, 100)
        self.tableWidget.setColumnWidth(4, 150)
        self.tableWidget.setColumnWidth(5, 150)
        self.tableWidget.setColumnWidth(6, 100)
        self.tableWidget.setColumnWidth(7, 100)
        self.tableWidget.setColumnWidth(8, 150)
        self.tableWidget.setColumnWidth(9, 200)
        self.tableWidget.setColumnWidth(10, 100)

        #print("whr_sql2 :"+str(self.whr_sql2))
        self.tableWidget.setHorizontalHeaderLabels([
            'Serial Id ', 'Recipt ID.', ' Truck Sr. No ', 'Vehical No.',
            'No. Bags', 'Release Date', 'Release Time', 'Net. Wt.', 'Tare Wt.',
            'Gross Wt.', 'Storage Name'
        ])

        connection = sqlite3.connect("fci.db")
        if (self.login_user_role in ['SUPER_ADMIN', 'ADMIN', 'SUPERVISOR']):
            results = connection.execute(
                "SELECT SERIAL_ID,(SELECT A.BATCH_ID_DISPLAY FROM BATCH_MST A WHERE A.BATCH_ID=BATCH_ID) as BATCH_ID,CURR_TRUCK_CNT||MANNUAL_INS_FLG,VEHICLE_NO,printf(\"%3d\", ACCPTED_BAGS) ,SUBSTR(IFNULL(SECOND_WT_CREATED_ON,FIRST_WT_CRTEATED_ON),1,11) AS RELEASE_DATE,SUBSTR(IFNULL(SECOND_WT_CREATED_ON,FIRST_WT_CRTEATED_ON),11,6) AS RELEASE_TIME,printf(\"%6d\", NET_WEIGHT_VAL) as NET_WEIGHT_VAL,printf(\"%6d\", TARE_WT_VAL) as TARE_WT_VAL,printf(\"%6d\", GROSS_WT_VAL) as GROSS_WT_VAL,TARGET_STORAGE FROM WEIGHT_MST_FCI_VW "
                + str(self.whr_sql2))

        else:
            results = connection.execute(
                "SELECT SERIAL_ID,(SELECT A.BATCH_ID_DISPLAY FROM BATCH_MST A WHERE A.BATCH_ID=BATCH_ID) as BATCH_ID,CURR_TRUCK_CNT,VEHICLE_NO,printf(\"%3d\", ACCPTED_BAGS) ,SUBSTR(IFNULL(SECOND_WT_CREATED_ON,FIRST_WT_CRTEATED_ON),1,11) AS RELEASE_DATE,SUBSTR(IFNULL(SECOND_WT_CREATED_ON,FIRST_WT_CRTEATED_ON),11,6) AS RELEASE_TIME,printf(\"%6d\", NET_WEIGHT_VAL) as NET_WEIGHT_VAL,printf(\"%6d\", TARE_WT_VAL) as TARE_WT_VAL,printf(\"%6d\", GROSS_WT_VAL) as GROSS_WT_VAL,TARGET_STORAGE FROM WEIGHT_MST_FCI_VW "
                + str(self.whr_sql2))
        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number,
                                         QTableWidgetItem(str(data)))
                #self.lineEdit.setText("")
        connection.close()
        #self.tableWidget.resizeColumnsToContents()
        #self.tableWidget.resizeRowsToContents()
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
Exemplo n.º 33
0
    def show_window_list_with_tablewidget(self):
        self.window_list_with_tablewidget.setupUi(self)
        try:
            mobiles_list = db_operations.get_mobile_phones()
        except Exception as e:
            print(e)
            return
        row = 0
        for mobile_phone in mobiles_list:
            self.window_list_with_tablewidget.tbl_list.insertRow(row)
            cell = QTableWidgetItem(str(mobile_phone.id_mobile_phone))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 0, cell)
            cell = QTableWidgetItem(mobile_phone.brand)
            self.window_list_with_tablewidget.tbl_list.setItem(row, 1, cell)
            cell = QTableWidgetItem(mobile_phone.model)
            self.window_list_with_tablewidget.tbl_list.setItem(row, 2, cell)
            cell = QTableWidgetItem(mobile_phone.os)
            self.window_list_with_tablewidget.tbl_list.setItem(row, 3, cell)
            cell = QTableWidgetItem(str(mobile_phone.memory))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 4, cell)
            cell = QTableWidgetItem(str(mobile_phone.price))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 5, cell)
            cell = QTableWidgetItem(str(mobile_phone.deal))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 6, cell)
            cell = QTableWidgetItem(str(mobile_phone.technology))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 7, cell)
            try:
                if pathlib.Path(mobile_phone.photo_path).is_file():
                    image = QLabel()
                    pixmap = QPixmap(
                        mobile_phone.photo_path).scaledToHeight(50)
                    image.setPixmap(pixmap)
                    self.window_list_with_tablewidget.tbl_list.setCellWidget(
                        row, 8, image)
            except Exception as e:
                print(e)
                return

            row += 1
        self.window_list_with_tablewidget.btn_delete.clicked.connect(
            self.btn_clicked_delete)
        self.window_list_with_tablewidget.btn_update.clicked.connect(
            self.btn_clicked_update)
        return
Exemplo n.º 34
0
    def s_select_all_data(self):
        sql_str = ""
        self.s_delete_all_records()
        font = QtGui.QFont()
        font.setPointSize(10)
        self.tableWidget.setFont(font)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)

        self.tableWidget.setHorizontalHeaderLabels([
            'Audit Id.', 'Created On', 'User Name', 'Message', 'Audit Type',
            'Role'
        ])
        if (str(self.login_user_role) == 'SUPER_ADMIN'):
            sql_str = "select A.AUDIT_ID,A.CREATED_ON,B.FIRST_NAME||' '||B.LAST_NAME as NAME,A.MESSAGE,A.AUDIT_TYPE,B.ROLE FROM AUDIT_MST A INNER JOIN  USERS_MST B ON A.USER_ID=B.USER_ID "
        elif (str(self.login_user_role) == 'ADMIN'):
            sql_str = "select A.AUDIT_ID,A.CREATED_ON,B.FIRST_NAME||' '||B.LAST_NAME as NAME,A.MESSAGE,A.AUDIT_TYPE,B.ROLE FROM AUDIT_MST A INNER JOIN  USERS_MST B ON A.USER_ID=B.USER_ID AND B.USER_ID IN (SELECT USER_ID FROM ADMINS_USER_IDS_VW)"

        elif (str(self.login_user_role) == 'SUPERVISOR'):
            sql_str = "select A.AUDIT_ID,A.CREATED_ON,B.FIRST_NAME||' '||B.LAST_NAME as NAME,A.MESSAGE,A.AUDIT_TYPE,B.ROLE FROM AUDIT_MST A INNER JOIN  USERS_MST B ON A.USER_ID=B.USER_ID AND B.USER_ID IN (SELECT USER_ID FROM SUPERVISORS_USER_IDS_VW)"

        else:
            sql_str = "select A.AUDIT_ID,A.CREATED_ON,B.FIRST_NAME||' '||B.LAST_NAME as NAME,A.MESSAGE,A.AUDIT_TYPE,B.ROLE FROM AUDIT_MST A INNER JOIN  USERS_MST B ON A.USER_ID=B.USER_ID AND B.USER_ID= '" + str(
                self.login_user_id) + "'"

        if (str(self.comboBox.currentText()) != 'ALL'):
            sql_str = sql_str + " AND (B.FIRST_NAME||' '||B.LAST_NAME||'('||B.ROLE||')') = '" + str(
                self.comboBox.currentText()) + "'"

        if (str(self.comboBox_2.currentText()) != 'ALL'):
            sql_str = sql_str + " AND A.AUDIT_TYPE='" + str(
                self.comboBox_2.currentText()) + "'"

        connection = sqlite3.connect("fci.db")
        print("sql:" + str(sql_str))
        results = connection.execute(sql_str)
        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number,
                                         QTableWidgetItem(str(data)))
        connection.close()
        #self.tableWidget.resizeColumnsToContents()
        self.tableWidget.resizeRowsToContents()
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
Exemplo n.º 35
0
    def select_all_data(self):
        self.delete_all_records()

        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setColumnWidth(0, 100)
        self.tableWidget.setColumnWidth(1, 100)
        self.tableWidget.setColumnWidth(2, 200)
        self.tableWidget.setColumnWidth(3, 100)
        self.tableWidget.setColumnWidth(4, 150)
        self.tableWidget.setColumnWidth(5, 150)
        self.tableWidget.setColumnWidth(6, 100)
        self.tableWidget.setColumnWidth(7, 100)
        self.tableWidget.setColumnWidth(8, 150)
        self.tableWidget.setColumnWidth(9, 200)
        self.tableWidget.setColumnWidth(10, 100)

        self.tableWidget.setHorizontalHeaderLabels([
            'Slip.No', ' Truck Sr. No ', 'Vehical No.', 'No. Bags', 'Material',
            'Release Date', 'Release Time', 'Net. Wt.', 'Tare Wt.',
            'Gross Wt.', 'Target Location'
        ])
        '''
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(False)
        font.setUnderline(False)
        #font.setWeight(50)
        self.tableWidget.setFont(font)
        '''
        connection = sqlite3.connect("fci.db")
        results = connection.execute(
            "SELECT printf(\"%06d\", SERIAL_ID) as SERIAL_ID,CURR_TRUCK_CNT,VEHICLE_NO,ACCPTED_BAGS,MATERIAL_NAME,SUBSTR(IFNULL(SECOND_WT_CREATED_ON,FIRST_WT_CRTEATED_ON),1,11) AS RELEASE_DATE,SUBSTR(IFNULL(SECOND_WT_CREATED_ON,FIRST_WT_CRTEATED_ON),11,6) AS RELEASE_TIME,IFNULL(NET_WEIGHT_VAL,0),IFNULL(TARE_WT_VAL,0),IFNULL(GROSS_WT_VAL,0),TARGET_STORAGE FROM WEIGHT_MST_FCI_VW WHERE BATCH_ID in (SELECT BATCH_ID FROM GLOBAL_VAR)"
        )
        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number,
                                         QTableWidgetItem(str(data)))
                #self.lineEdit.setText("")
        connection.close()
        #self.tableWidget.resizeColumnsToContents()
        #self.tableWidget.resizeRowsToContents()
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
Exemplo n.º 36
0
 def list_report_data(self):
     self.delete_all_records()
     font = QtGui.QFont()
     font.setPointSize(10)
     self.tableWidget.setFont(font)
     
     self.tableWidget.setHorizontalHeaderLabels(['ID', 'Backup Type', 'Created On','File Name','Status'])               
     connection = sqlite3.connect("wt.db")  
     results=connection.execute("select ID,BACKUP_TYPE,BACKUP_ON, FILE_NAME,STATUS FROM BACKUP_HIST order by BACKUP_ON desc ")            
     for row_number, row_data in enumerate(results):            
         self.tableWidget.insertRow(row_number)
         for column_number, data in enumerate(row_data):
             self.tableWidget.setItem(row_number,column_number,QTableWidgetItem(str(data)))                
     self.tableWidget.resizeColumnsToContents()
     self.tableWidget.resizeRowsToContents()
     self.tableWidget.horizontalHeader().setStretchLastSection(True)
     self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
     connection.close() 
Exemplo n.º 37
0
    def load(self):
        conn = psycopg2.connect("dbname=test1_data user=jm password=123")
        cur = conn.cursor()
        cur.execute('select * from table1')
        rows = cur.fetchall()
        row = cur.rowcount  #取得记录个数,用于设置表格的行数
        vol = len(rows[0])  #取得字段数,用于设置表格的列数
        cur.close()
        conn.close()

        self.table.setRowCount(row)
        self.table.setColumnCount(vol)

        for i in range(row):
            for j in range(vol):
                temp_data = rows[i][j]  #临时记录,不能直接插入表格
                data = QTableWidgetItem(str(temp_data))  #转换后可插入表格
                self.table.setItem(i, j, data)
Exemplo n.º 38
0
    def getLayerList(self):
        s_rows = self.g_alti_conn.execSelect("select count(*) from geometry_columns")
        if not s_rows or s_rows[0][0] == 0:
            QMessageBox.warning(self,
                                "Error",
                                "There is no tables with geometry",
                                QMessageBox.Ok)
            return

        s_rows = self.g_alti_conn.execSelect("select F_TABLE_SCHEMA, F_TABLE_NAME, F_GEOMETRY_COLUMN, COORD_DIMENSION, SRID \
                                              from geometry_columns")
        for s_row_num, s_row in enumerate(s_rows):
            self.LayerList.insertRow(s_row_num)
            for s_col_num, s_col in enumerate(s_row):
                self.LayerList.setItem(s_row_num, s_col_num, QTableWidgetItem(str(s_col)))

        self.LayerList.resizeColumnsToContents()
        self.LayerList.setEditTriggers(QAbstractItemView.NoEditTriggers)
Exemplo n.º 39
0
    def select_all_edited(self):
        self.delete_all_records()
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.tableWidget.setFont(font)

        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setColumnWidth(0, 100)
        self.tableWidget.setColumnWidth(1, 200)
        self.tableWidget.setColumnWidth(2, 200)
        self.tableWidget.setColumnWidth(3, 250)
        self.tableWidget.setColumnWidth(4, 200)
        self.tableWidget.setColumnWidth(5, 150)
        #print("whr_sql2 :"+str(self.whr_sql2))
        self.from_dt = self.lineEdit.text() + " " + str(
            self.comboBox.currentText()) + ":" + str(
                self.comboBox_2.currentText()) + ":00"
        self.to_dt = self.lineEdit_2.text() + " " + str(
            self.comboBox_8.currentText()) + ":" + str(
                self.comboBox_7.currentText()) + ":00"

        self.tableWidget.setHorizontalHeaderLabels([
            'Serial Id ', 'Vehical No.', 'No.Of.Bags', 'Net. Wt.', 'Tare Wt.',
            'Gorss.Wt'
        ])

        connection = sqlite3.connect("fci.db")
        results = connection.execute(
            "SELECT printf(\"%06d\", SERIAL_ID),VEHICLE_NO,printf(\"%3d\", ACCPTED_BAGS) ,printf(\"%6d\", NET_WEIGHT_VAL) as NET_WEIGHT_VAL,printf(\"%6d\", TARE_WT_VAL) as TARE_WT_VAL,printf(\"%6d\", GROSS_WT_VAL) as GROSS_WT_VAL FROM WEIGHT_MST_FCI_VW WHERE EDITED_FLG='Yes' AND FIRST_WT_CRTEATED_ON between '"
            + str(self.from_dt) + "' and '" + str(self.to_dt) + "'")
        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number,
                                         QTableWidgetItem(str(data)))
                #self.lineEdit.setText("")
        connection.close()
        #self.tableWidget.resizeColumnsToContents()
        #self.tableWidget.resizeRowsToContents()
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
Exemplo n.º 40
0
    def list_report_data(self):
        self.delete_all_records()
        font = QtGui.QFont()
        font.setPointSize(10)
        self.tableWidget.setFont(font)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setHorizontalHeaderLabels([
            'Serial ID.', ' Vehical.No ', 'Party Name', 'Material Name',
            'Gross Wt. Date', 'Gross Wt.(Kg)', 'Tare Wt.Date', 'Tare Wt.(Kg)',
            'Net Wt. (Kg)', 'Total Amount'
        ])
        self.r_count = 0
        connection = sqlite3.connect("wt.db")
        print("from_date :" + str(self.from_date) + " to_date :" +
              str(self.to_date))
        self.cr_where_clause()
        print(" Where clause :" + self.whr_str)
        if (self.whr_str != ""):
            results = connection.execute(
                "SELECT SERIAL_ID_DISPLY,VEHICLE_NO,PARTY_NAME,MATERIAL_NAME,"
                +
                "GROSS_WT_DATE ,GROSS_WT_VAL, TARE_WT_DATE ,TARE_WT_VAL  ,NET_WEIGHT_VAL, (IFNULL(GROSS_WT_RATE,0)+ IFNULL(TARE_WT_RATE,0)) as TOTAL_AMT FROM WEIGHT_MST_VW "
                + self.whr_str)

        else:
            results = connection.execute(
                "SELECT printf(\"%04d\", SERIAL_ID) as SERIAL_ID,VEHICLE_NO,PARTY_NAME,MATERIAL_NAME,"
                +
                "GROSS_WT_DATE ,GROSS_WT_VAL, TARE_WT_DATE ,TARE_WT_VAL  ,NET_WEIGHT_VAL, (IFNULL(GROSS_WT_RATE,0)+ IFNULL(TARE_WT_RATE,0)) as TOTAL_AMT FROM WEIGHT_MST_VW"
            )
        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            self.r_count = int(self.r_count) + 1
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number,
                                         QTableWidgetItem(str(data)))
        self.tableWidget.resizeColumnsToContents()
        self.tableWidget.resizeRowsToContents()
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
        connection.close()
        self.create_pdf_new()
        #print("Total Records :"+str(self.r_count))
        if (int(self.r_count) > 0):
            self.pushButton_5.setEnabled(True)
    def __init__(self, parent, items):
        QDialog.__init__(self, parent)
        Ui_DeleteMatchingFromDeviceDialog.__init__(self)
        self.setupUi(self)

        self.explanation.setText('<p>'+_('All checked books will be '
                                   '<b>permanently deleted</b> from your '
                                   'device. Please verify the list.')+'</p>')
        self.buttonBox.accepted.connect(self.accepted)
        self.buttonBox.rejected.connect(self.rejected)
        self.table.cellClicked.connect(self.cell_clicked)
        self.table.setSelectionMode(QAbstractItemView.NoSelection)
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels(
                                    ['', _('Location'), _('Title'), _('Author'),
                                      _('Date'), _('Format'), _('Path')])
        rows = 0
        for card in items:
            rows += len(items[card][1])
        self.table.setRowCount(rows)
        row = 0
        for card in items:
            (model,books) = items[card]
            for (id,book) in books:
                item = QTableWidgetItem()
                item.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
                item.setCheckState(Qt.Checked)
                item.setData(Qt.UserRole, (model, id, book.path))
                self.table.setItem(row, 0, item)
                self.table.setItem(row, 1, tableItem(card))
                self.table.setItem(row, 2, titleTableItem(book.title))
                self.table.setItem(row, 3, authorTableItem(book))
                self.table.setItem(row, 4, dateTableItem(book.datetime))
                self.table.setItem(row, 5, centeredTableItem(book.path.rpartition('.')[2]))
                self.table.setItem(row, 6, tableItem(book.path))
                row += 1
        self.table.setCurrentCell(0, 1)
        self.table.resizeColumnsToContents()
        self.table.setSortingEnabled(True)
        self.table.sortByColumn(2, Qt.AscendingOrder)
        self.table.setCurrentCell(0, 1)
Exemplo n.º 42
0
 def __init__(self, txt):
     QTableWidgetItem.__init__(self, txt)
     self.initial_value = txt
     self.current_value = txt
     self.previous_value = txt
Exemplo n.º 43
0
class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):

    def __init__(self, parent, db, id_to_select, select_sort, select_link):
        QDialog.__init__(self, parent)
        Ui_EditAuthorsDialog.__init__(self)
        self.setupUi(self)
        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        try:
            self.table_column_widths = \
                        gprefs.get('manage_authors_table_widths', None)
            geom = gprefs.get('manage_authors_dialog_geometry', bytearray(''))
            self.restoreGeometry(QByteArray(geom))
        except:
            pass

        self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
        self.buttonBox.accepted.connect(self.accepted)

        # Set up the column headings
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table.setColumnCount(3)
        self.down_arrow_icon = QIcon(I('arrow-down.png'))
        self.up_arrow_icon = QIcon(I('arrow-up.png'))
        self.blank_icon = QIcon(I('blank.png'))
        self.auth_col = QTableWidgetItem(_('Author'))
        self.table.setHorizontalHeaderItem(0, self.auth_col)
        self.auth_col.setIcon(self.blank_icon)
        self.aus_col = QTableWidgetItem(_('Author sort'))
        self.table.setHorizontalHeaderItem(1, self.aus_col)
        self.aus_col.setIcon(self.up_arrow_icon)
        self.aul_col = QTableWidgetItem(_('Link'))
        self.table.setHorizontalHeaderItem(2, self.aul_col)
        self.aus_col.setIcon(self.blank_icon)

        # Add the data
        self.authors = {}
        auts = db.get_authors_with_ids()
        self.table.setRowCount(len(auts))
        select_item = None
        for row, (id, author, sort, link) in enumerate(auts):
            author = author.replace('|', ',')
            self.authors[id] = (author, sort, link)
            aut = tableItem(author)
            aut.setData(Qt.UserRole, id)
            sort = tableItem(sort)
            link = tableItem(link)
            self.table.setItem(row, 0, aut)
            self.table.setItem(row, 1, sort)
            self.table.setItem(row, 2, link)
            if id_to_select in (id, author):
                if select_sort:
                    select_item = sort
                elif select_link:
                    select_item = link
                else:
                    select_item = aut
        self.table.resizeColumnsToContents()
        if self.table.columnWidth(2) < 200:
            self.table.setColumnWidth(2, 200)

        # set up the cellChanged signal only after the table is filled
        self.table.cellChanged.connect(self.cell_changed)

        # set up sort buttons
        self.sort_by_author.setCheckable(True)
        self.sort_by_author.setChecked(False)
        self.sort_by_author.clicked.connect(self.do_sort_by_author)
        self.author_order = 1

        self.table.sortByColumn(1, Qt.AscendingOrder)
        self.sort_by_author_sort.clicked.connect(self.do_sort_by_author_sort)
        self.sort_by_author_sort.setCheckable(True)
        self.sort_by_author_sort.setChecked(True)
        self.author_sort_order = 1

        self.recalc_author_sort.clicked.connect(self.do_recalc_author_sort)
        self.auth_sort_to_author.clicked.connect(self.do_auth_sort_to_author)

        # Position on the desired item
        if select_item is not None:
            self.table.setCurrentItem(select_item)
            self.table.editItem(select_item)
            self.start_find_pos = select_item.row() * 2 + select_item.column()
        else:
            self.table.setCurrentCell(0, 0)
            self.start_find_pos = -1

        # set up the search box
        self.find_box.initialize('manage_authors_search')
        self.find_box.lineEdit().returnPressed.connect(self.do_find)
        self.find_box.editTextChanged.connect(self.find_text_changed)
        self.find_button.clicked.connect(self.do_find)
        self.find_button.setDefault(True)

        l = QLabel(self.table)
        self.not_found_label = l
        l.setFrameStyle(QFrame.StyledPanel)
        l.setAutoFillBackground(True)
        l.setText(_('No matches found'))
        l.setAlignment(Qt.AlignVCenter)
        l.resize(l.sizeHint())
        l.move(10,20)
        l.setVisible(False)
        self.not_found_label.move(40, 40)
        self.not_found_label_timer = QTimer()
        self.not_found_label_timer.setSingleShot(True)
        self.not_found_label_timer.timeout.connect(
                self.not_found_label_timer_event, type=Qt.QueuedConnection)

        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested .connect(self.show_context_menu)

    def save_state(self):
        self.table_column_widths = []
        for c in range(0, self.table.columnCount()):
            self.table_column_widths.append(self.table.columnWidth(c))
        gprefs['manage_authors_table_widths'] = self.table_column_widths
        gprefs['manage_authors_dialog_geometry'] = bytearray(self.saveGeometry())

    def resizeEvent(self, *args):
        QDialog.resizeEvent(self, *args)
        if self.table_column_widths is not None:
            for c,w in enumerate(self.table_column_widths):
                self.table.setColumnWidth(c, w)
        else:
            # the vertical scroll bar might not be rendered, so might not yet
            # have a width. Assume 25. Not a problem because user-changed column
            # widths will be remembered
            w = self.table.width() - 25 - self.table.verticalHeader().width()
            w /= self.table.columnCount()
            for c in range(0, self.table.columnCount()):
                self.table.setColumnWidth(c, w)
        self.save_state()

    def show_context_menu(self, point):
        self.context_item = self.table.itemAt(point)
        case_menu = QMenu(_('Change Case'))
        action_upper_case = case_menu.addAction(_('Upper Case'))
        action_lower_case = case_menu.addAction(_('Lower Case'))
        action_swap_case = case_menu.addAction(_('Swap Case'))
        action_title_case = case_menu.addAction(_('Title Case'))
        action_capitalize = case_menu.addAction(_('Capitalize'))

        action_upper_case.triggered.connect(self.upper_case)
        action_lower_case.triggered.connect(self.lower_case)
        action_swap_case.triggered.connect(self.swap_case)
        action_title_case.triggered.connect(self.title_case)
        action_capitalize.triggered.connect(self.capitalize)

        m = self.au_context_menu = QMenu()
        ca = m.addAction(_('Copy'))
        ca.triggered.connect(self.copy_to_clipboard)
        ca = m.addAction(_('Paste'))
        ca.triggered.connect(self.paste_from_clipboard)
        m.addSeparator()

        if self.context_item is not None and self.context_item.column() == 0:
            ca = m.addAction(_('Copy to author sort'))
            ca.triggered.connect(self.copy_au_to_aus)
        else:
            ca = m.addAction(_('Copy to author'))
            ca.triggered.connect(self.copy_aus_to_au)
        m.addSeparator()
        m.addMenu(case_menu)
        m.exec_(self.table.mapToGlobal(point))

    def copy_to_clipboard(self):
        cb = QApplication.clipboard()
        cb.setText(unicode(self.context_item.text()))

    def paste_from_clipboard(self):
        cb = QApplication.clipboard()
        self.context_item.setText(cb.text())

    def upper_case(self):
        self.context_item.setText(icu_upper(unicode(self.context_item.text())))

    def lower_case(self):
        self.context_item.setText(icu_lower(unicode(self.context_item.text())))

    def swap_case(self):
        self.context_item.setText(unicode(self.context_item.text()).swapcase())

    def title_case(self):
        from calibre.utils.titlecase import titlecase
        self.context_item.setText(titlecase(unicode(self.context_item.text())))

    def capitalize(self):
        from calibre.utils.icu import capitalize
        self.context_item.setText(capitalize(unicode(self.context_item.text())))

    def copy_aus_to_au(self):
        row = self.context_item.row()
        dest = self.table.item(row, 0)
        dest.setText(self.context_item.text())

    def copy_au_to_aus(self):
        row = self.context_item.row()
        dest = self.table.item(row, 1)
        dest.setText(self.context_item.text())

    def not_found_label_timer_event(self):
        self.not_found_label.setVisible(False)

    def find_text_changed(self):
        self.start_find_pos = -1

    def do_find(self):
        self.not_found_label.setVisible(False)
        # For some reason the button box keeps stealing the RETURN shortcut.
        # Steal it back
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
        self.buttonBox.button(QDialogButtonBox.Ok).setAutoDefault(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setAutoDefault(False)
        st = icu_lower(unicode(self.find_box.currentText()))

        for i in range(0, self.table.rowCount()*2):
            self.start_find_pos = (self.start_find_pos + 1) % (self.table.rowCount()*2)
            r = (self.start_find_pos/2)%self.table.rowCount()
            c = self.start_find_pos % 2
            item = self.table.item(r, c)
            text = icu_lower(unicode(item.text()))
            if st in text:
                self.table.setCurrentItem(item)
                self.table.setFocus(True)
                return
        # Nothing found. Pop up the little dialog for 1.5 seconds
        self.not_found_label.setVisible(True)
        self.not_found_label_timer.start(1500)

    def do_sort_by_author(self):
        self.author_order = 1 if self.author_order == 0 else 0
        self.table.sortByColumn(0, self.author_order)
        self.sort_by_author.setChecked(True)
        self.sort_by_author_sort.setChecked(False)
        self.auth_col.setIcon(self.down_arrow_icon if self.author_order
                                                    else self.up_arrow_icon)
        self.aus_col.setIcon(self.blank_icon)

    def do_sort_by_author_sort(self):
        self.author_sort_order = 1 if self.author_sort_order == 0 else 0
        self.table.sortByColumn(1, self.author_sort_order)
        self.sort_by_author.setChecked(False)
        self.sort_by_author_sort.setChecked(True)
        self.aus_col.setIcon(self.down_arrow_icon if self.author_sort_order
                                                    else self.up_arrow_icon)
        self.auth_col.setIcon(self.blank_icon)

    def accepted(self):
        self.save_state()
        self.result = []
        for row in range(0,self.table.rowCount()):
            id   = int(self.table.item(row, 0).data(Qt.UserRole))
            aut  = unicode(self.table.item(row, 0).text()).strip()
            sort = unicode(self.table.item(row, 1).text()).strip()
            link = unicode(self.table.item(row, 2).text()).strip()
            orig_aut,orig_sort,orig_link = self.authors[id]
            if orig_aut != aut or orig_sort != sort or orig_link != link:
                self.result.append((id, orig_aut, aut, sort, link))

    def do_recalc_author_sort(self):
        self.table.cellChanged.disconnect()
        for row in range(0,self.table.rowCount()):
            item = self.table.item(row, 0)
            aut  = unicode(item.text()).strip()
            c = self.table.item(row, 1)
            # Sometimes trailing commas are left by changing between copy algs
            c.setText(author_to_author_sort(aut).rstrip(','))
        self.table.setFocus(Qt.OtherFocusReason)
        self.table.cellChanged.connect(self.cell_changed)

    def do_auth_sort_to_author(self):
        self.table.cellChanged.disconnect()
        for row in range(0,self.table.rowCount()):
            item = self.table.item(row, 1)
            aus  = unicode(item.text()).strip()
            c = self.table.item(row, 0)
            # Sometimes trailing commas are left by changing between copy algs
            c.setText(aus)
        self.table.setFocus(Qt.OtherFocusReason)
        self.table.cellChanged.connect(self.cell_changed)

    def cell_changed(self, row, col):
        if col == 0:
            item = self.table.item(row, 0)
            aut  = unicode(item.text()).strip()
            amper = aut.find('&')
            if amper >= 0:
                error_dialog(self.parent(), _('Invalid author name'),
                        _('Author names cannot contain & characters.')).exec_()
                aut = aut.replace('&', '%')
                self.table.item(row, 0).setText(aut)
            c = self.table.item(row, 1)
            c.setText(author_to_author_sort(aut))
            item = c
        else:
            item  = self.table.item(row, col)
        self.table.setCurrentItem(item)
        self.table.scrollToItem(item)
Exemplo n.º 44
0
class TagListEditor(QDialog, Ui_TagListEditor):

    def __init__(self, window, cat_name, tag_to_match, data, sorter):
        QDialog.__init__(self, window)
        Ui_TagListEditor.__init__(self)
        self.setupUi(self)
        self.search_box.setMinimumContentsLength(25)

        # Put the category name into the title bar
        t = self.windowTitle()
        self.setWindowTitle(t + ' (' + cat_name + ')')
        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        # Get saved geometry info
        try:
            self.table_column_widths = \
                        gprefs.get('tag_list_editor_table_widths', None)
        except:
            pass

        # initialization
        self.to_rename = {}
        self.to_delete = set([])
        self.original_names = {}
        self.all_tags = {}
        self.counts = {}

        for k,v,count in data:
            self.all_tags[v] = k
            self.counts[v] = count
            self.original_names[k] = v

        # Set up the column headings
        self.down_arrow_icon = QIcon(I('arrow-down.png'))
        self.up_arrow_icon = QIcon(I('arrow-up.png'))
        self.blank_icon = QIcon(I('blank.png'))

        self.table.setColumnCount(3)
        self.name_col = QTableWidgetItem(_('Tag'))
        self.table.setHorizontalHeaderItem(0, self.name_col)
        self.name_col.setIcon(self.up_arrow_icon)
        self.count_col = QTableWidgetItem(_('Count'))
        self.table.setHorizontalHeaderItem(1, self.count_col)
        self.count_col.setIcon(self.blank_icon)
        self.was_col = QTableWidgetItem(_('Was'))
        self.table.setHorizontalHeaderItem(2, self.was_col)
        self.count_col.setIcon(self.blank_icon)

        # Capture clicks on the horizontal header to sort the table columns
        hh = self.table.horizontalHeader()
        hh.setSectionsClickable(True)
        hh.sectionClicked.connect(self.header_clicked)
        hh.sectionResized.connect(self.table_column_resized)
        self.name_order = 0
        self.count_order = 1
        self.was_order = 1

        # Add the data
        select_item = None
        self.table.setRowCount(len(self.all_tags))
        for row,tag in enumerate(sorted(self.all_tags.keys(), key=sorter)):
            item = NameTableWidgetItem(tag)
            item.setData(Qt.UserRole, self.all_tags[tag])
            item.setFlags(item.flags() | Qt.ItemIsSelectable | Qt.ItemIsEditable)
            self.table.setItem(row, 0, item)
            if tag == tag_to_match:
                select_item = item
            item = CountTableWidgetItem(self.counts[tag])
            # only the name column can be selected
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            self.table.setItem(row, 1, item)
            item = QTableWidgetItem('')
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            self.table.setItem(row, 2, item)

        # Scroll to the selected item if there is one
        if select_item is not None:
            self.table.setCurrentItem(select_item)

        self.delete_button.clicked.connect(self.delete_tags)
        self.rename_button.clicked.connect(self.rename_tag)
        self.table.itemDoubleClicked.connect(self._rename_tag)
        self.table.itemChanged.connect(self.finish_editing)

        self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
        self.buttonBox.accepted.connect(self.accepted)

        self.search_box.initialize('tag_list_search_box_' + cat_name)
        self.search_box.editTextChanged.connect(self.find_text_changed)
        self.search_button.clicked.connect(self.search_clicked)
        self.search_button.setDefault(True)

        self.start_find_pos = -1

        try:
            geom = gprefs.get('tag_list_editor_dialog_geometry', None)
            if geom is not None:
                self.restoreGeometry(QByteArray(geom))
            else:
                self.resize(self.sizeHint()+QSize(150, 100))
        except:
            pass

    def find_text_changed(self):
        self.start_find_pos = -1

    def search_clicked(self):
        search_for = icu_lower(unicode(self.search_box.text()))
        if not search_for:
            error_dialog(self, _('Find'), _('You must enter some text to search for'),
                         show=True, show_copy_button=False)
            return
        rows = self.table.rowCount()
        for i in range(0, rows):
            self.start_find_pos += 1
            if self.start_find_pos >= rows:
                self.start_find_pos = 0
            item = self.table.item(self.start_find_pos, 0)
            if search_for in icu_lower(unicode(item.text())):
                self.table.setCurrentItem(item)
                return
        info_dialog(self, _('Find'), _('No tag found'), show=True, show_copy_button=False)

    def table_column_resized(self, col, old, new):
        self.table_column_widths = []
        for c in range(0, self.table.columnCount()):
            self.table_column_widths.append(self.table.columnWidth(c))

    def resizeEvent(self, *args):
        QDialog.resizeEvent(self, *args)
        if self.table_column_widths is not None:
            for c,w in enumerate(self.table_column_widths):
                self.table.setColumnWidth(c, w)
        else:
            # the vertical scroll bar might not be rendered, so might not yet
            # have a width. Assume 25. Not a problem because user-changed column
            # widths will be remembered
            w = self.table.width() - 25 - self.table.verticalHeader().width()
            w /= self.table.columnCount()
            for c in range(0, self.table.columnCount()):
                self.table.setColumnWidth(c, w)

    def save_geometry(self):
        gprefs['tag_list_editor_table_widths'] = self.table_column_widths
        gprefs['tag_list_editor_dialog_geometry'] = bytearray(self.saveGeometry())

    def finish_editing(self, item):
        if not item.text():
                error_dialog(self, _('Item is blank'),
                             _('An item cannot be set to nothing. Delete it instead.')).exec_()
                item.setText(item.previous_text())
                return
        if item.text() != item.initial_text():
            id_ = int(item.data(Qt.UserRole))
            self.to_rename[id_] = unicode(item.text())
            orig = self.table.item(item.row(), 2)
            self.table.blockSignals(True)
            orig.setData(Qt.DisplayRole, item.initial_text())
            self.table.blockSignals(False)

    def rename_tag(self):
        item = self.table.item(self.table.currentRow(), 0)
        self._rename_tag(item)

    def _rename_tag(self, item):
        if item is None:
            error_dialog(self, _('No item selected'),
                         _('You must select one item from the list of Available items.')).exec_()
            return
        self.table.editItem(item)

    def delete_tags(self):
        deletes = self.table.selectedItems()
        if not deletes:
            error_dialog(self, _('No items selected'),
                         _('You must select at least one item from the list.')).exec_()
            return
        ct = ', '.join([unicode(item.text()) for item in deletes])
        if not question_dialog(self, _('Are you sure?'),
            '<p>'+_('Are you sure you want to delete the following items?')+'<br>'+ct):
            return
        row = self.table.row(deletes[0])
        for item in deletes:
            id = int(item.data(Qt.UserRole))
            self.to_delete.add(id)
            self.table.removeRow(self.table.row(item))

        if row >= self.table.rowCount():
            row = self.table.rowCount() - 1
        if row >= 0:
            self.table.scrollToItem(self.table.item(row, 0))

    def header_clicked(self, idx):
        if idx == 0:
            self.do_sort_by_name()
        elif idx == 1:
            self.do_sort_by_count()
        else:
            self.do_sort_by_was()

    def do_sort_by_name(self):
        self.name_order = 1 if self.name_order == 0 else 0
        self.table.sortByColumn(0, self.name_order)
        self.name_col.setIcon(self.down_arrow_icon if self.name_order
                                                    else self.up_arrow_icon)
        self.count_col.setIcon(self.blank_icon)
        self.was_col.setIcon(self.blank_icon)

    def do_sort_by_count(self):
        self.count_order = 1 if self.count_order == 0 else 0
        self.table.sortByColumn(1, self.count_order)
        self.count_col.setIcon(self.down_arrow_icon if self.count_order
                                                    else self.up_arrow_icon)
        self.name_col.setIcon(self.blank_icon)
        self.was_col.setIcon(self.blank_icon)

    def do_sort_by_was(self):
        self.was_order = 1 if self.was_order == 0 else 0
        self.table.sortByColumn(2, self.was_order)
        self.was_col.setIcon(self.down_arrow_icon if self.was_order
                                                    else self.up_arrow_icon)
        self.name_col.setIcon(self.blank_icon)
        self.count_col.setIcon(self.blank_icon)

    def accepted(self):
        self.save_geometry()
Exemplo n.º 45
0
 def setText(self, txt):
     self.current_value = txt
     QTableWidgetItem.setText(txt)
Exemplo n.º 46
0
 def __init__(self, text, icon):
     QTableWidgetItem.__init__(self, text)
     if icon:
         self.setIcon(icon)
Exemplo n.º 47
0
class TagListEditor(QDialog, Ui_TagListEditor):

    def __init__(self, window, cat_name, tag_to_match, get_book_ids, sorter):
        QDialog.__init__(self, window)
        Ui_TagListEditor.__init__(self)
        self.setupUi(self)
        self.search_box.setMinimumContentsLength(25)

        # Put the category name into the title bar
        t = self.windowTitle()
        self.setWindowTitle(t + ' (' + cat_name + ')')
        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        # Get saved geometry info
        try:
            self.table_column_widths = \
                        gprefs.get('tag_list_editor_table_widths', None)
        except:
            pass

        # initialization
        self.to_rename = {}
        self.to_delete = set([])
        self.all_tags = {}
        self.original_names = {}

        self.ordered_tags = []
        self.sorter = sorter
        self.get_book_ids = get_book_ids

        # Set up the column headings
        self.down_arrow_icon = QIcon(I('arrow-down.png'))
        self.up_arrow_icon = QIcon(I('arrow-up.png'))
        self.blank_icon = QIcon(I('blank.png'))

        # Capture clicks on the horizontal header to sort the table columns
        hh = self.table.horizontalHeader()
        hh.setSectionsClickable(True)
        hh.sectionClicked.connect(self.header_clicked)
        hh.sectionResized.connect(self.table_column_resized)
        self.name_order = 0
        self.count_order = 1
        self.was_order = 1

        self.table.setItemDelegate(EditColumnDelegate(self.table))

        # Add the data
        select_item = self.fill_in_table(None, tag_to_match)

        # Scroll to the selected item if there is one
        if select_item is not None:
            self.table.setCurrentItem(select_item)

        self.delete_button.clicked.connect(self.delete_tags)
        self.rename_button.clicked.connect(self.rename_tag)
        self.undo_button.clicked.connect(self.undo_edit)
        self.table.itemDoubleClicked.connect(self._rename_tag)
        self.table.itemChanged.connect(self.finish_editing)

        self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
        self.buttonBox.accepted.connect(self.accepted)

        self.search_box.initialize('tag_list_search_box_' + cat_name)
        self.search_button.clicked.connect(self.all_matching_clicked)
        self.search_button.setDefault(True)

        self.apply_vl_checkbox.clicked.connect(self.vl_box_changed)

        self.table.setEditTriggers(QTableWidget.EditKeyPressed)

        try:
            geom = gprefs.get('tag_list_editor_dialog_geometry', None)
            if geom is not None:
                self.restoreGeometry(QByteArray(geom))
            else:
                self.resize(self.sizeHint()+QSize(150, 100))
        except:
            pass

    def vl_box_changed(self):
        self.fill_in_table(None, None)

    def fill_in_table(self, tags, tag_to_match):
        data = self.get_book_ids(self.apply_vl_checkbox.isChecked())
        self.all_tags = {}
        for k,v,count in data:
            self.all_tags[v] = {'key': k, 'count': count, 'cur_name': v,
                                'is_deleted': k in self.to_delete}
            self.original_names[k] = v
        self.ordered_tags = sorted(self.all_tags.keys(), key=self.sorter)
        if tags is None:
            tags = self.ordered_tags

        select_item = None
        self.table.blockSignals(True)
        self.table.clear()
        self.table.setColumnCount(3)
        self.name_col = QTableWidgetItem(_('Tag'))
        self.table.setHorizontalHeaderItem(0, self.name_col)
        self.name_col.setIcon(self.up_arrow_icon)
        self.count_col = QTableWidgetItem(_('Count'))
        self.table.setHorizontalHeaderItem(1, self.count_col)
        self.count_col.setIcon(self.blank_icon)
        self.was_col = QTableWidgetItem(_('Was'))
        self.table.setHorizontalHeaderItem(2, self.was_col)
        self.count_col.setIcon(self.blank_icon)

        self.table.setRowCount(len(tags))

        for row,tag in enumerate(tags):
            item = NameTableWidgetItem()
            item.set_is_deleted(self.all_tags[tag]['is_deleted'])
            _id = self.all_tags[tag]['key']
            item.setData(Qt.UserRole, _id)
            item.set_initial_text(tag)
            if _id in self.to_rename:
                item.setText(self.to_rename[_id])
            else:
                item.setText(tag)
            item.setFlags(item.flags() | Qt.ItemIsSelectable | Qt.ItemIsEditable)
            self.table.setItem(row, 0, item)
            if tag == tag_to_match:
                select_item = item

            item = CountTableWidgetItem(self.all_tags[tag]['count'])
            # only the name column can be selected
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            self.table.setItem(row, 1, item)

            item = QTableWidgetItem()
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            if _id in self.to_rename or _id in self.to_delete:
                item.setData(Qt.DisplayRole, tag)
            self.table.setItem(row, 2, item)
        self.table.blockSignals(False)
        return select_item

    def all_matching_clicked(self):
        for i in range(0, self.table.rowCount()):
            item = self.table.item(i, 0)
            tag = item.initial_text()
            self.all_tags[tag]['cur_name'] = item.text()
            self.all_tags[tag]['is_deleted'] = item.is_deleted
        search_for = icu_lower(unicode_type(self.search_box.text()))
        if len(search_for) == 0:
            self.fill_in_table(None, None)
        result = []
        for k in self.ordered_tags:
            if search_for in icu_lower(unicode_type(self.all_tags[k]['cur_name'])):
                result.append(k)
        self.fill_in_table(result, None)

    def table_column_resized(self, col, old, new):
        self.table_column_widths = []
        for c in range(0, self.table.columnCount()):
            self.table_column_widths.append(self.table.columnWidth(c))

    def resizeEvent(self, *args):
        QDialog.resizeEvent(self, *args)
        if self.table_column_widths is not None:
            for c,w in enumerate(self.table_column_widths):
                self.table.setColumnWidth(c, w)
        else:
            # the vertical scroll bar might not be rendered, so might not yet
            # have a width. Assume 25. Not a problem because user-changed column
            # widths will be remembered
            w = self.table.width() - 25 - self.table.verticalHeader().width()
            w /= self.table.columnCount()
            for c in range(0, self.table.columnCount()):
                self.table.setColumnWidth(c, w)

    def save_geometry(self):
        gprefs['tag_list_editor_table_widths'] = self.table_column_widths
        gprefs['tag_list_editor_dialog_geometry'] = bytearray(self.saveGeometry())

    def finish_editing(self, item):
        if not item.text():
            error_dialog(self, _('Item is blank'), _(
                'An item cannot be set to nothing. Delete it instead.'), show=True)
            item.setText(item.initial_text())
            return
        if item.text() != item.initial_text():
            id_ = int(item.data(Qt.UserRole))
            self.to_rename[id_] = unicode_type(item.text())
            orig = self.table.item(item.row(), 2)
            self.table.blockSignals(True)
            orig.setData(Qt.DisplayRole, item.initial_text())
            self.table.blockSignals(False)

    def undo_edit(self):
        indexes = self.table.selectionModel().selectedRows()
        if not indexes:
            error_dialog(self, _('No item selected'),
                         _('You must select one item from the list of Available items.')).exec_()
            return

        if not confirm(
            _('Do you really want to undo your changes?'),
            'tag_list_editor_undo'):
            return
        self.table.blockSignals(True)
        for idx in indexes:
            row = idx.row()
            item = self.table.item(row, 0)
            item.setText(item.initial_text())
            item.set_is_deleted(False)
            self.to_delete.discard(int(item.data(Qt.UserRole)))
            self.to_rename.pop(int(item.data(Qt.UserRole)), None)
            self.table.item(row, 2).setData(Qt.DisplayRole, '')
        self.table.blockSignals(False)

    def rename_tag(self):
        item = self.table.item(self.table.currentRow(), 0)
        self._rename_tag(item)

    def _rename_tag(self, item):
        if item is None:
            error_dialog(self, _('No item selected'),
                         _('You must select one item from the list of Available items.')).exec_()
            return
        col_zero_item = self.table.item(item.row(), 0)
        if col_zero_item.is_deleted:
            if not question_dialog(self, _('Undelete item?'),
                   '<p>'+_('That item is deleted. Do you want to undelete it?')+'<br>'):
                return
            col_zero_item.set_is_deleted(False)
            self.to_delete.discard(int(col_zero_item.data(Qt.UserRole)))
            orig = self.table.item(col_zero_item.row(), 2)
            self.table.blockSignals(True)
            orig.setData(Qt.DisplayRole, '')
            self.table.blockSignals(False)
        else:
            self.table.editItem(item)

    def delete_tags(self):
        deletes = self.table.selectedItems()
        if not deletes:
            error_dialog(self, _('No items selected'),
                         _('You must select at least one item from the list.')).exec_()
            return

        to_del = []
        to_undel = []
        for item in deletes:
            if item.is_deleted:
                to_undel.append(item)
            else:
                to_del.append(item)
        if to_del:
            ct = ', '.join([unicode_type(item.text()) for item in to_del])
            if not confirm(
                '<p>'+_('Are you sure you want to delete the following items?')+'<br>'+ct,
                'tag_list_editor_delete'):
                return
        if to_undel:
            ct = ', '.join([unicode_type(item.text()) for item in to_undel])
            if not confirm(
                '<p>'+_('Are you sure you want to undelete the following items?')+'<br>'+ct,
                'tag_list_editor_undelete'):
                return
        row = self.table.row(deletes[0])
        for item in deletes:
            if item.is_deleted:
                item.set_is_deleted(False)
                self.to_delete.discard(int(item.data(Qt.UserRole)))
                orig = self.table.item(item.row(), 2)
                self.table.blockSignals(True)
                orig.setData(Qt.DisplayRole, '')
                self.table.blockSignals(False)
            else:
                id = int(item.data(Qt.UserRole))
                self.to_delete.add(id)
                item.set_is_deleted(True)
                orig = self.table.item(item.row(), 2)
                self.table.blockSignals(True)
                orig.setData(Qt.DisplayRole, item.initial_text())
                self.table.blockSignals(False)
        if row >= self.table.rowCount():
            row = self.table.rowCount() - 1
        if row >= 0:
            self.table.scrollToItem(self.table.item(row, 0))

    def header_clicked(self, idx):
        if idx == 0:
            self.do_sort_by_name()
        elif idx == 1:
            self.do_sort_by_count()
        else:
            self.do_sort_by_was()

    def do_sort_by_name(self):
        self.name_order = 1 if self.name_order == 0 else 0
        self.table.sortByColumn(0, self.name_order)
        self.name_col.setIcon(self.down_arrow_icon if self.name_order
                                                    else self.up_arrow_icon)
        self.count_col.setIcon(self.blank_icon)
        self.was_col.setIcon(self.blank_icon)

    def do_sort_by_count(self):
        self.count_order = 1 if self.count_order == 0 else 0
        self.table.sortByColumn(1, self.count_order)
        self.count_col.setIcon(self.down_arrow_icon if self.count_order
                                                    else self.up_arrow_icon)
        self.name_col.setIcon(self.blank_icon)
        self.was_col.setIcon(self.blank_icon)

    def do_sort_by_was(self):
        self.was_order = 1 if self.was_order == 0 else 0
        self.table.sortByColumn(2, self.was_order)
        self.was_col.setIcon(self.down_arrow_icon if self.was_order
                                                    else self.up_arrow_icon)
        self.name_col.setIcon(self.blank_icon)
        self.count_col.setIcon(self.blank_icon)

    def accepted(self):
        self.save_geometry()
Exemplo n.º 48
0
 def __init__(self):
     QTableWidgetItem.__init__(self)
     self.initial_value = ''
     self.current_value = ''
     self.is_deleted = False
Exemplo n.º 49
0
    def setup_row(self, field_metadata, row, col):
        item = QTableWidgetItem(col)
        self.opt_columns.setItem(row, 1, item)

        if col.startswith('#'):
            fm = self.custcols[col]
        else:
            fm = field_metadata[col]

        if col == 'title':
            coltype = _('Text')
        elif col == 'ondevice':
            coltype = _('Yes/No with text')
        else:
            dt = fm['datatype']
            if fm['is_multiple']:
                dt = '*' + dt
            coltype = self.column_desc[dt]
        item = QTableWidgetItem(coltype)
        self.opt_columns.setItem(row, 2, item)

        desc = fm['display'].get('description', "")
        item = QTableWidgetItem(desc)
        self.opt_columns.setItem(row, 3, item)

        item = QTableWidgetItem(fm['name'])
        item.setData(Qt.UserRole, (col))
        self.opt_columns.setItem(row, 0, item)

        if col.startswith('#'):
            item.setData(Qt.DecorationRole, (QIcon(I('column.png'))))
        flags = Qt.ItemIsEnabled|Qt.ItemIsSelectable
        if col != 'ondevice':
            flags |= Qt.ItemIsUserCheckable
        item.setFlags(flags)
        if col != 'ondevice':
            item.setCheckState(Qt.Unchecked if col in self.hidden_cols else
                    Qt.Checked)
Exemplo n.º 50
0
 def setData(self, role, data):
     if role == Qt.EditRole:
         self.previous_value = self.current_value
         self.current_value = data
     QTableWidgetItem.setData(self, role, data)
Exemplo n.º 51
0
    def setup_row(self, field_metadata, row, col, oldkey=None):
        flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable

        item = QTableWidgetItem(col)
        item.setFlags(flags)
        self.opt_columns.setItem(row, 1, item)

        if col.startswith('#'):
            fm = self.custcols[oldkey if oldkey is not None else col]
        else:
            fm = field_metadata[col]

        if col == 'title':
            coltype = _('Text')
        elif col == 'ondevice':
            coltype = _('Yes/No with text')
        else:
            dt = fm['datatype']
            if fm['is_multiple']:
                if col == 'authors' or fm.get('display', {}).get('is_names', False):
                    coltype = _('Ampersand separated text, shown in the Tag browser')
                else:
                    coltype = self.column_desc['*' + dt]
            else:
                coltype = self.column_desc[dt]
        coltype_info = (coltype if oldkey is None else
                          ' ' + _('(lookup name was {0}) {1}'.format(oldkey, coltype)))

        item = QTableWidgetItem(coltype_info)
        item.setFlags(flags)
        self.opt_columns.setItem(row, 2, item)

        desc = fm['display'].get('description', "")
        item = QTableWidgetItem(desc)
        item.setFlags(flags)
        self.opt_columns.setItem(row, 3, item)

        item = QTableWidgetItem(fm['name'])
        item.setData(Qt.UserRole, (col))
        item.setFlags(flags)
        self.opt_columns.setItem(row, 0, item)

        if col.startswith('#'):
            item.setData(Qt.DecorationRole, (QIcon(I('column.png'))))
        if col != 'ondevice':
            flags |= Qt.ItemIsUserCheckable
        item.setFlags(flags)
        if col != 'ondevice':
            item.setCheckState(Qt.Unchecked if col in self.hidden_cols else
                    Qt.Checked)
Exemplo n.º 52
0
 def __init__(self, count):
     QTableWidgetItem.__init__(self, str(count))
     self._count = count
Exemplo n.º 53
0
 def __init__(self, text):
     if text is None:
         text = ''
     QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
     self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
Exemplo n.º 54
0
    def __init__(self, window, cat_name, tag_to_match, data, sorter):
        QDialog.__init__(self, window)
        Ui_TagListEditor.__init__(self)
        self.setupUi(self)
        self.search_box.setMinimumContentsLength(25)

        # Put the category name into the title bar
        t = self.windowTitle()
        self.setWindowTitle(t + ' (' + cat_name + ')')
        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        # Get saved geometry info
        try:
            self.table_column_widths = \
                        gprefs.get('tag_list_editor_table_widths', None)
        except:
            pass

        # initialization
        self.to_rename = {}
        self.to_delete = set([])
        self.original_names = {}
        self.all_tags = {}
        self.counts = {}

        for k,v,count in data:
            self.all_tags[v] = k
            self.counts[v] = count
            self.original_names[k] = v

        # Set up the column headings
        self.down_arrow_icon = QIcon(I('arrow-down.png'))
        self.up_arrow_icon = QIcon(I('arrow-up.png'))
        self.blank_icon = QIcon(I('blank.png'))

        self.table.setColumnCount(3)
        self.name_col = QTableWidgetItem(_('Tag'))
        self.table.setHorizontalHeaderItem(0, self.name_col)
        self.name_col.setIcon(self.up_arrow_icon)
        self.count_col = QTableWidgetItem(_('Count'))
        self.table.setHorizontalHeaderItem(1, self.count_col)
        self.count_col.setIcon(self.blank_icon)
        self.was_col = QTableWidgetItem(_('Was'))
        self.table.setHorizontalHeaderItem(2, self.was_col)
        self.count_col.setIcon(self.blank_icon)

        # Capture clicks on the horizontal header to sort the table columns
        hh = self.table.horizontalHeader()
        hh.setSectionsClickable(True)
        hh.sectionClicked.connect(self.header_clicked)
        hh.sectionResized.connect(self.table_column_resized)
        self.name_order = 0
        self.count_order = 1
        self.was_order = 1

        # Add the data
        select_item = None
        self.table.setRowCount(len(self.all_tags))
        for row,tag in enumerate(sorted(self.all_tags.keys(), key=sorter)):
            item = NameTableWidgetItem(tag)
            item.setData(Qt.UserRole, self.all_tags[tag])
            item.setFlags(item.flags() | Qt.ItemIsSelectable | Qt.ItemIsEditable)
            self.table.setItem(row, 0, item)
            if tag == tag_to_match:
                select_item = item
            item = CountTableWidgetItem(self.counts[tag])
            # only the name column can be selected
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            self.table.setItem(row, 1, item)
            item = QTableWidgetItem('')
            item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable))
            self.table.setItem(row, 2, item)

        # Scroll to the selected item if there is one
        if select_item is not None:
            self.table.setCurrentItem(select_item)

        self.delete_button.clicked.connect(self.delete_tags)
        self.rename_button.clicked.connect(self.rename_tag)
        self.table.itemDoubleClicked.connect(self._rename_tag)
        self.table.itemChanged.connect(self.finish_editing)

        self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
        self.buttonBox.accepted.connect(self.accepted)

        self.search_box.initialize('tag_list_search_box_' + cat_name)
        self.search_box.editTextChanged.connect(self.find_text_changed)
        self.search_button.clicked.connect(self.search_clicked)
        self.search_button.setDefault(True)

        self.start_find_pos = -1

        try:
            geom = gprefs.get('tag_list_editor_dialog_geometry', None)
            if geom is not None:
                self.restoreGeometry(QByteArray(geom))
            else:
                self.resize(self.sizeHint()+QSize(150, 100))
        except:
            pass
Exemplo n.º 55
0
 def __init__(self, number, is_read_only=False):
     QTableWidgetItem.__init__(self, '', QTableWidgetItem.UserType)
     self.setData(Qt.DisplayRole, number)
     if is_read_only:
         self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
Exemplo n.º 56
0
    def populate_table_row(self, row, line):

        if True:
            checkbox_cell = QTableWidgetItem()
            checkbox_cell.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            checkbox_cell.setCheckState(Qt.Unchecked)
            checkbox_cell.setToolTip(_('Checked sections will be included in <i>all</i> split books.<br>Default title will still be taken from the first <i>selected</i> section, and section order will remain as shown.')+
                                     '<br>'+_('Use Context Menu (right-click) on selected sections to check or uncheck all selected sections.'))
            self.setItem(row, 0, checkbox_cell)

        href = line['href']
        if line['anchor']:
            href = "%s#%s"%(href,line['anchor'])

        href_cell = ReadOnlyTableWidgetItem(href)
        href_cell.setToolTip(line['sample']+SAMPLE_NOTE)
        self.setItem(row, 1, href_cell)

        if 'guide' in line:
            guide = "(%s):%s"%line['guide']
        else:
            guide = ""
        guide_cell = ReadOnlyTableWidgetItem(guide)
        guide_cell.setToolTip(_("Indicates 'special' pages: copyright, titlepage, etc."))
        self.setItem(row, 2, guide_cell)

        toc_str = "|".join(line['toc'])
        toc_cell = QTableWidgetItem(toc_str)
        toc_cell.setData(Qt.UserRole, toc_str)
        toc_cell.setToolTip(_('''Click and copy hotkey to copy text.
Double-click to edit ToC entry.
Pipes(|) divide different ToC entries to the same place.'''))
        self.setItem(row, 3, toc_cell)
Exemplo n.º 57
0
 def __init__(self, val, sort, idx=0):
     self.sort = sort
     self.sort_idx = idx
     QTableWidgetItem.__init__(self, val)
     self.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
Exemplo n.º 58
0
    def __init__(self, parent, db, id_to_select, select_sort, select_link):
        QDialog.__init__(self, parent)
        Ui_EditAuthorsDialog.__init__(self)
        self.setupUi(self)
        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        try:
            self.table_column_widths = \
                        gprefs.get('manage_authors_table_widths', None)
            geom = gprefs.get('manage_authors_dialog_geometry', bytearray(''))
            self.restoreGeometry(QByteArray(geom))
        except:
            pass

        self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
        self.buttonBox.accepted.connect(self.accepted)

        # Set up the column headings
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table.setColumnCount(3)
        self.down_arrow_icon = QIcon(I('arrow-down.png'))
        self.up_arrow_icon = QIcon(I('arrow-up.png'))
        self.blank_icon = QIcon(I('blank.png'))
        self.auth_col = QTableWidgetItem(_('Author'))
        self.table.setHorizontalHeaderItem(0, self.auth_col)
        self.auth_col.setIcon(self.blank_icon)
        self.aus_col = QTableWidgetItem(_('Author sort'))
        self.table.setHorizontalHeaderItem(1, self.aus_col)
        self.aus_col.setIcon(self.up_arrow_icon)
        self.aul_col = QTableWidgetItem(_('Link'))
        self.table.setHorizontalHeaderItem(2, self.aul_col)
        self.aus_col.setIcon(self.blank_icon)

        # Add the data
        self.authors = {}
        auts = db.get_authors_with_ids()
        self.table.setRowCount(len(auts))
        select_item = None
        for row, (id, author, sort, link) in enumerate(auts):
            author = author.replace('|', ',')
            self.authors[id] = (author, sort, link)
            aut = tableItem(author)
            aut.setData(Qt.UserRole, id)
            sort = tableItem(sort)
            link = tableItem(link)
            self.table.setItem(row, 0, aut)
            self.table.setItem(row, 1, sort)
            self.table.setItem(row, 2, link)
            if id_to_select in (id, author):
                if select_sort:
                    select_item = sort
                elif select_link:
                    select_item = link
                else:
                    select_item = aut
        self.table.resizeColumnsToContents()
        if self.table.columnWidth(2) < 200:
            self.table.setColumnWidth(2, 200)

        # set up the cellChanged signal only after the table is filled
        self.table.cellChanged.connect(self.cell_changed)

        # set up sort buttons
        self.sort_by_author.setCheckable(True)
        self.sort_by_author.setChecked(False)
        self.sort_by_author.clicked.connect(self.do_sort_by_author)
        self.author_order = 1

        self.table.sortByColumn(1, Qt.AscendingOrder)
        self.sort_by_author_sort.clicked.connect(self.do_sort_by_author_sort)
        self.sort_by_author_sort.setCheckable(True)
        self.sort_by_author_sort.setChecked(True)
        self.author_sort_order = 1

        self.recalc_author_sort.clicked.connect(self.do_recalc_author_sort)
        self.auth_sort_to_author.clicked.connect(self.do_auth_sort_to_author)

        # Position on the desired item
        if select_item is not None:
            self.table.setCurrentItem(select_item)
            self.table.editItem(select_item)
            self.start_find_pos = select_item.row() * 2 + select_item.column()
        else:
            self.table.setCurrentCell(0, 0)
            self.start_find_pos = -1

        # set up the search box
        self.find_box.initialize('manage_authors_search')
        self.find_box.lineEdit().returnPressed.connect(self.do_find)
        self.find_box.editTextChanged.connect(self.find_text_changed)
        self.find_button.clicked.connect(self.do_find)
        self.find_button.setDefault(True)

        l = QLabel(self.table)
        self.not_found_label = l
        l.setFrameStyle(QFrame.StyledPanel)
        l.setAutoFillBackground(True)
        l.setText(_('No matches found'))
        l.setAlignment(Qt.AlignVCenter)
        l.resize(l.sizeHint())
        l.move(10,20)
        l.setVisible(False)
        self.not_found_label.move(40, 40)
        self.not_found_label_timer = QTimer()
        self.not_found_label_timer.setSingleShot(True)
        self.not_found_label_timer.timeout.connect(
                self.not_found_label_timer_event, type=Qt.QueuedConnection)

        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested .connect(self.show_context_menu)
 def __init__(self, text):
     QTableWidgetItem.__init__(self, text)
     self.setFlags(Qt.ItemIsEnabled)
     self.sort = text.lower()