print tableview or model in pyqt5 - python

I'm trying to print a content of a tableview or the model taht running the table view by using the Qprinter and QPrintPreviewDialog but the best that I can get is an empty table like this
this is my code for handle Preview
def handlePreview(self):
dialog = QtPrintSupport.QPrintPreviewDialog()
dialog.setFixedSize(1000,690)
dialog.paintRequested.connect(self.handlePaintRequest)
dialog.exec_()
nd for the handle Print Request
def handlePaintRequest(self, printer):
#printer = QPrinter()
database = QSqlDatabase("QPSQL")
database.setHostName("localhost")
database.setDatabaseName("database")
database.setUserName("username")
database.setPassword("password")
database.open()
self.model_hjd = QSqlTableModel(db=database)
self.model_hjd.setTable('transactions')
date = str(self.dateEdit_10.text())
date_2 = str(self.dateEdit_14.text())
self.model_hjd.select()
filter_ft = "date_d BETWEEN '%s' AND '%s'" % (date, date_2)
self.model_hjd.setFilter(filter_ft)
rows = self.model_hjd.rowCount()
columns = self.model_hjd.columnCount()
print (rows)
print (columns)
self.model_hjd = QtGui.QStandardItemModel(self)
#self.tableView_22.setModel(self.model_hjd)
#self.table.setModel(self.model_hjd)
for row in range(self.model_hjd.rowCount()):
for column in range(self.model_hjd.columnCount()):
myitem = self.model_hjd.item(row,column)
if myitem is None:
item = QtGui.QStandardItem("")
self.model_hjd.setItem(row, column, item)
document = QtGui.QTextDocument()
cursor = QtGui.QTextCursor(document)
#model_hjd = self.tableView_22.model_hjd()
table = cursor.insertTable(rows, columns)
for row in range(rows):
for column in range(table.columns()):
cursor.insertText(self.model_hjd.item(row, column))
cursor.movePosition(QtGui.QTextCursor.NextCell)
document.print_(printer)
Is there any idea or a hit to fix this?

I find a way to make it work, but it need more correction
def handlePaintRequest(self, printer):
database = QSqlDatabase("QPSQL")
database.setHostName("localhost")
database.setDatabaseName("database)
database.setUserName("user")
database.setPassword("password")
database.open()
model_hjd = QSqlTableModel(db=database)
model_hjd.setTable('transactions')
model_hjd.setHeaderData(0, Qt.Horizontal,"id")
model_hjd.setHeaderData(1, Qt.Horizontal,"montant")
model_hjd.setHeaderData(2, Qt.Horizontal,"medecin")
model_hjd.setHeaderData(3, Qt.Horizontal,"patient")
model_hjd.setHeaderData(4, Qt.Horizontal,"acte")
model_hjd.setHeaderData(5, Qt.Horizontal,"date")
model_hjd.setHeaderData(6, Qt.Horizontal,"temps")
model_hjd.setEditStrategy(QSqlTableModel.OnManualSubmit)
model_hjd.removeColumns(7,1)
#model_hjd.removeColumn(5)
date = str(self.dateEdit_10.text())
date_2 = str(self.dateEdit_14.text())
self.tableView_22.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
model_hjd.setSort(6, Qt.DescendingOrder)
self.tableView_22.setModel(model_hjd)
model_hjd.select()
filter_ft = "date_d BETWEEN '%s' AND '%s'" % (date, date_2)
model_hjd.setFilter(filter_ft)
self.model = QtGui.QStandardItemModel(self)
item = QtGui.QStandardItem()
self.model.appendRow(item)
self.model.setData(self.model.index(0, 5), "", 0)
self.tableView_22.resizeColumnsToContents()
self.tableView_22.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
# Selection of columns
self.selectionModel = self.tableView_22.selectionModel()
self.tableView_22.setModel(model_hjd)
document = QTextDocument()
cursor = QTextCursor(document)
tableFormat = QTextTableFormat()
tableFormat.setBorder(0.2)
tableFormat.setBorderStyle(3)
tableFormat.setCellSpacing(0);
tableFormat.setTopMargin(0);
tableFormat.setCellPadding(4)
table = cursor.insertTable(model_hjd.rowCount() + 1, model_hjd.columnCount(), tableFormat)
### get headers
myheaders = []
for i in range(0, model_hjd.columnCount()):
myheader = model_hjd.headerData(i, Qt.Horizontal)
cursor.insertText(myheader)
cursor.movePosition(QTextCursor.NextCell)
for row in range(0, model_hjd.rowCount()):
for col in range(0, model_hjd.columnCount()):
index = model_hjd.index( row, col )
cursor.insertText(str(index.data()))
cursor.movePosition(QTextCursor.NextCell)
document.print_(printer)
the result
###########################################
Is there a way to fix the date and time format?
and add line in to the table

Related

PyQt5: Get row number from button-menu action in QTableView index-widget

Basically, I have a QTableView and the last column of each row contains a QMenu where if triggered, the row should be deleted. I tried the code below, but if I click on the menu that is in a row number > 1, the returned rowNum is -1:
Code:
def addrowIntable(self, a, b):
Column1 = QStandardItem("%s" % (a))
Column2 = QStandardItem("%s" % (b))
actionBTN = QPushButton("")
actionMenu = QMenu()
self.RemList = QtWidgets.QAction("Remove row", actionMenu)
actionMenu.addAction(self.RemList)
actionMenu.raise_()
actionBTN.setMenu(actionMenu)
self.rulesWhitelistWidgetModel.appendRow([Column1, Column2])
self.rulesWhiteListFileTBL.setIndexWidget(
self.rulesWhitelistWidgetModel.index(self.rulesWhitelistWidgetModel.rowCount() - 1,
self.rulesWhiteListFileTBL.model().columnCount() - 1), actionBTN)
self.RemList.triggered.connect(lambda: self.deleteRow("Hello"))
def deleteRow(self, str):
rowNum = self.rulesWhiteListFileTBL.rowAt(self.rulesWhiteListFileTBL.viewport().mapFromGlobal(self.sender().parent().pos()).y())
print(self.rulesWhiteListFileTBL.indexAt(self.sender().parent().pos()).row())
print(rowNum)
I just need to know which row number was the sender from inside deleteRow where I could then use model.removeRow() to delete it.
The main reason why your code doesn't work as expected is because you set the menu as the parent of the action. A menu is a popup window, so its position will be in global coordinates, whereas you want the position relative to the table. A simple way to achieve this is to make the button the parent of the action instead.
The following revision of your code should do what you want:
def addrowIntable(self, a, b):
Column1 = QStandardItem("%s" % (a))
Column2 = QStandardItem("%s" % (b))
actionBTN = QPushButton()
actionMenu = QMenu()
actionRem = QtWidgets.QAction("Remove row", actionBTN)
actionMenu.addAction(actionRem)
actionBTN.setMenu(actionMenu)
self.rulesWhitelistWidgetModel.appendRow([Column1, Column2])
self.rulesWhiteListFileTBL.setIndexWidget(Column2.index(), actionBTN)
actionRem.triggered.connect(lambda: self.deleteRow("Hello"))
def deleteRow(self, str):
pos = self.sender().parent().pos()
index = self.rulesWhiteListFileTBL.indexAt(pos)
self.rulesWhitelistWidgetModel.removeRow(index.row())

convert to date format in pyqt5 Qprinter

Is there a way to convert to date format will use the Printer and QTextDocument the result always show in the date and time like in the image?
this is my code
def handlePaintRequest(self, printer):
model_hjd = QSqlTableModel()
model_hjd.setTable('transactions')
date = str(self.dateEdit_10.text())
date_2 = str(self.dateEdit_14.text())
self.tableView_22.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
model_hjd.setSort(6, Qt.DescendingOrder)
self.tableView_22.setModel(model_hjd)
model_hjd.select()
filter_ft = "date_d BETWEEN '%s' AND '%s'" % (date, date_2)
model_hjd.setFilter(filter_ft)
self.tableView_22.setModel(model_hjd)
document = QTextDocument()
cursor = QTextCursor(document)
tableFormat = QTextTableFormat()
table = cursor.insertTable(model_hjd.rowCount() + 1, model_hjd.columnCount(), tableFormat)
myheaders = []
for i in range(0, model_hjd.columnCount()):
myheader = model_hjd.headerData(i, Qt.Horizontal)
cursor.insertText(myheader)
cursor.movePosition(QTextCursor.NextCell)
for row in range(0, model_hjd.rowCount()):
for col in range(0, model_hjd.columnCount()):
index = model_hjd.index( row, col )
cursor.insertText(str(index.data()))
cursor.movePosition(QTextCursor.NextCell)
document.print_(printer)
but the result in date and time are like this
You could use a custom function to format the different types of data in your table, e.g.
#staticmethod
def to_string(entry):
if isinstance(entry, (QtCore.QDate, QtCore.QTime, QtCore.QDateTime)):
return entry.toString(Qt.SystemLocaleShortDate)
else:
return str(entry)
def handlePaintRequest(self, printer):
....
cursor.insertText(self.to_string(index.data()))
....

How to convert text table to dataframe

I am trying to scrape the "PRINCIPAL STOCKHOLDERS" table from the linktext fileand convert it to a csv file. Right now I am only half successful. Namely, I can locate the table and parse it but somehow I cannot convert the text table to a standard one. My code is attached. Can someone help me with it?
url = r'https://www.sec.gov/Archives/edgar/data/1034239/0000950124-97-003372.txt'
# Different approach, the first approach does not work
filing_url = requests.get(url)
content = filing_url.text
splited_data = content.split('\n')
table_title = 'PRINCIPAL STOCKHOLDERS'
END_TABLE_LINE = '- ------------------------'
def find_no_line_start_table(table_title,splited_data):
found_no_lines = []
for index, line in enumerate(splited_data):
if table_title in line:
found_no_lines.append(index)
return found_no_lines
table_start = find_no_line_start_table(table_title,splited_data)
# I need help with locating the table. If I locate the table use the above function, it will return two locations and I have to manually choose the correct one.
table_start = table_start[1]
def get_start_data_table(table_start, splited_data):
for index, row in enumerate(splited_data[table_start:]):
if '<C>' in row:
return table_start + index
def get_end_table(start_table_data, splited_data ):
for index, row in enumerate(splited_data[start_table_data:]):
if END_TABLE_LINE in row:
return start_table_data + index
def row(l):
l = l.split()
number_columns = 8
if len(l) >= number_columns:
data_row = [''] * number_columns
first_column_done = False
index = 0
for w in l:
if not first_column_done:
data_row[0] = ' '.join([data_row[0], w])
if ':' in w:
first_column_done = True
else:
index += 1
data_row[index] = w
return data_row
start_line = get_start_data_table(table_start, splited_data)
end_line = get_end_table(start_line, splited_data)
table = splited_data[start_line : end_line]
# I also need help with convert the text table to a CSV file, somehow the following function does not #recognize my column.
def take_table(table):
owner = []
Num_share = []
middle = []
middle_1 = []
middle_2 = []
middle_3 = []
prior_offering = []
after_offering = []
for r in table:
data_row = row(r)
if data_row:
col_1, col_2, col_3, col_4, col_5, col_6, col_7, col_8 = data_row
owner.append(col_1)
Num_share.append(col_2)
middle.append(col_3)
middle_1.append(col_4)
middle_2.append(col_5)
middle_3.append(col_6)
prior_offering.append(col_7)
after_offering.append(col_8)
table_data = {'owner': owner, 'Num_share': Num_share, 'middle': middle, 'middle_1': middle_1,
'middle_2': middle_2, 'middle_3': middle_3, 'prior_offering': prior_offering,
'after_offering': after_offering}
return table_data
#print (table)
dict_table = take_table(table)
a = pd.DataFrame(dict_table)
a.to_csv('trail.csv')
I think what you need to do is
pd.DataFrame.from_dict(dict_table)
instead of
pd.DataFrame(dict_table)

how to disable all columns apart from one column in Qtablewidget PYQT - python

Problem Statement:
Disable specific columns and enable specific row on bases of current row index.
I am working on Qtablewidget i tried following code this working fine for disable.
i wanted to enable tablewidget row contents on bases of row index .
when i clicked pushbutton that row should be enable.I am new to the stackoverflow please guide me.I am tring to enable tablewidget cell,pushbutton,combobox i am not getting please guide me how to enble particular row on bases of index.
Code :
self.tableWidget = QtGui.QTableWidget(self.centralwidget)
self.tableWidget.setColumnCount(4)
myresult = [(u'sandeep', u'checkbox'), (u'shivaraj', u'checkbox')]
for row, result in enumerate(myresult):
self.tableWidget.insertRow(self.tableWidget.rowCount())
for column, value in enumerate(result):
item = QtGui.QTableWidgetItem(str(value))
if column == 1:
if (value == "textbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(1)
self.tableWidget.setCellWidget(row, column, self.cb)
self.cb.setEnabled(False)#this is for combobox disable
elif (value == "checkbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(2)
self.tableWidget.setCellWidget(row, column, self.cb)
self.cb.setEnabled(False)#this is for combobox disable
self.tableWidget.setItem(row, column, item)
item.setFlags(QtCore.Qt.ItemIsEnabled)#this is for text non editable
self.btn_sell = QtGui.QPushButton('Edit')
self.btn_sell1 = QtGui.QPushButton('Delete')
self.btn_sell1.setEnabled(False)#this for button disble
self.tableWidget.setCellWidget(row, 2, self.btn_sell)
self.tableWidget.setCellWidget(row, 3, self.btn_sell1)
self.btn_sell.clicked.connect(self.edit)
def edit(self):
index = self.tableWidget.currentRow()
print index
self.table = QtGui.QTableWidget()
self.table.setGeometry(QtCore.QRect(220, 100, 881, 100))
self.table.setColumnCount(4)
self.table.setRowCount(1)
self.table.setColumnWidth(0, 120)
self.table.setColumnWidth(1, 500)
self.table.setColumnWidth(2, 120)
self.table.setColumnWidth(3, 120)
indexes = self.tableWidget.currentRow()
widget = self.tableWidget.cellWidget(indexes, 2)
# print widget
if isinstance(widget, QtGui.QComboBox):
h = str(widget.currentText())
if (h == "multiple_input"):
j = "checkbox"
elif (h == "description"):
j = "textbox"
if (j == "textbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(1)
self.table.setCellWidget(0, 2, self.cb)
[enter image description here][1]elif (j == "checkbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(2)
self.table.setCellWidget(0, 2, self.cb)
n = [str(self.tableWidget.item(indexes, 0).text())]
for x in n:
f = ''.join(map(str, x))
self.table.setItem(0, 0, QtGui.QTableWidgetItem(f))
n1 = [str(self.tableWidget.item(indexes, 1).text())]
# print n1
for i in n1:
s = ''.join(i)
self.table.setItem(0, 1, QtGui.QTableWidgetItem(s))
self.li = QtGui.QPushButton("Update")
self.table.setCellWidget(0, 3, self.li)
self.li.clicked.connect(self.edit_data)
self.table.show()
click on below link has image.
Try the above code:
Select row and click on edit button it will take the current index row values into the separate table `where we can edit and update the values.This is the one way i have tried to update the value it works fine.

How do I use the values from a QComboBox to edit a database (PyQt, Sqlite3, Python)

I have a system of editing data when the data is just text. I have added a combobox, and I want the data from that to be editable too. When the combobox is changed, and the edit button is clicked, I want the data to update in the database. How do I do that?
Here is the code for one of my outputted queries.
def click_btn_lessons(self):
self.screen_name = "lessons"
self.page_constants()
self.cur.execute("SELECT StudentID FROM StudentProfile")
students_students = self.cur.fetchall()
self.cur.execute("SELECT StudentID FROM Lessons")
students_lessons = self.cur.fetchall()
self.cur.execute("""SELECT s.studentID, s.FullName, l.LessonDate, r.RoadExerciseName, e.Rating
FROM StudentProfile s
LEFT JOIN Lessons l ON s.StudentID=l.StudentID
LEFT JOIN LessonExercises e ON l.LessonID=e.LessonID
LEFT JOIN RoadExerciseInfo r ON r.RoadExerciseID=e.RoadExerciseID
""")
self.all_data = self.cur.fetchall()
"""This section just removes black records"""
for student in students_students:
if student not in students_lessons:
for item in self.all_data:
if item[0] == student[0]:
self.all_data.remove(item)
self.table.setRowCount(len(self.all_data))
self.tableFields = ['check','Full name','Lesson date', 'Exercise', "Rating"]
self.table.setColumnCount(len(self.tableFields))
self.table.setHorizontalHeaderLabels(self.tableFields)
self.checkbox_list = []
for i, item in enumerate(self.all_data):
FullName = QtGui.QTableWidgetItem(str(item[1]))
LessonDate = QtGui.QTableWidgetItem(str(item[2]))
RoadExerciseName = QtGui.QTableWidgetItem(str(item[3]))
#This is the combobox and its items
Rating = QtGui.QComboBox()
for num in range(5):
Rating.addItem(str(num))
self.table.setItem(i, 1, FullName)
self.table.setItem(i, 2, LessonDate)
self.table.setItem(i, 3, RoadExerciseName)
#here is how the combobox isadded to the table
self.table.setCellWidget(i, 4, Rating)
#the checkbox items have to be ticked for them to be passed to the edit function
chkBoxItem = QtGui.QTableWidgetItem()
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
self.checkbox_list.append(chkBoxItem)
self.table.setItem(i, 0, self.checkbox_list[i])
FullName.setFlags(FullName.flags() & ~Qt.ItemIsEditable)
RoadExerciseName.setFlags(RoadExerciseName.flags() & ~Qt.ItemIsEditable)
self.name = None
self.changed_items = []
self.table.itemChanged.connect(self.log_change)
def log_change(self, item):
self.table.blockSignals(True)
item.setBackgroundColor(QtGui.QColor("red"))
self.table.blockSignals(False)
self.changed_items.append(item)
def click_btn_edit(self):
print("Updating")
for item in self.changed_items:
self.table.blockSignals(True)
item.setBackgroundColor(QtGui.QColor("white"))
self.table.blockSignals(False)
text, col, row = item.text(), item.column(), item.row()
new_data = self.all_data
for i, record in enumerate(self.all_data):
if i == row:
if self.checkbox_list[i].checkState() == QtCore.Qt.Checked:
#Below adds the new data to the database.
self.cur.execute("""UPDATE {0} SET {1} = ? WHERE {2} = ?""".format(self.table_edit_name,self.columnList[col],self.field_ID),(text,record[0],))
"""self.field_ID is the field name for the primary key, record[0]. This ensures data is entered in the correct record.
columnList is a list of columns in the record, in order.
self.table_edit_name is the name of the table involved."""

Categories