How to set the column text format of QTableWidget? - python

I want to show some data in table form. I took QTableWidget for it having multiple columns. One column of it will contain time(hh:mm format).
I also want user to edit any item of table but with corresponding format.
I was able to add data in QTableWidget but i couldn't set text format of time column.
This i want to achieve so that user can edit time only in hh:mm format.
If possible please write your answer code in python.

Since you want the user enter time date, I would suggest to reuse the already existing QDateTimeEdit class in the following way:
dateTime = QDateTimeEdit();
dateTime.setDisplayFormat("hh:mm");
dateTime.setFrame(False);
myTableWidget.setCellWidget(row, column, dateTime);
The user will be able to edit the "time data" this way in your table widget. Moreover, it will be also convenient due to the steps that can be applied.
If you really insist on reinventing this yourself, you can use a QLineEdit with custom validator againt the desired hh::mm format.
dateTime = QLineEdit();
dateTime.setValidator(QRegExpValidator(QRegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$")));
myTableWidget.setCellWidget(row, column, dateTime);

Related

Read "date" from table

In my GUI, made with Qt Designer, I have table, 6 columns and 5 rows(headers not count). In first column will be date in format "DD/MM/YY". How I can read and save to some variable those dates, for future use in pdf report? Dates will not be used in any operations, just copy from table and send to function that build pdf report, so they can be str format.
I tried this:
T=[]
for i in range(self.ui.table_Level_N.rowCount()):
T.append(self.ui.table_Level_N.item(i,0))
but got some strange text:
<PyQt5.QtWidgets.QTableWidgetItem object at 0x0000019A24D903A0>
I assumed that it read dates but not in right format.table_Level_N is my table.
You need to get the text from the QTableWidgetItem and append it to the list. Try this:
T = []
for i in range(self.ui.table_Level_N.rowCount()):
item = self.ui.table_Level_N.item(i, 0)
T.append(item.text())
This will give you the text of the cell in the format you want, which you can then use in your PDF report.

having issues formatting output to excel from dataframes, using xlsxwriter

I have a series of SQL database queries, that I am writing to Excel, using Xlswriter/Pandas.
I am using a simple global format, for font type and size.
Each table is different, so the only thing I want to do, is present a standard font and size.
format = workbook.add_format()
format.set_font_size(9)
format.set_font_name='Calibri'
for col_name in df1:
column_width=max(df1[col_name].astype(str).map(len).max(),len(col_name))
col_idx=df1.columns.get_loc(col_name)
if col_idx < 4:
column_width=column_width + 1
worksheet1.set_column(col_idx,col_idx,column_width,format)
writer.save()
This all work well, until I encounter a DATE.
There may be multiple date fields, or no date field in each Excel table
All the fonts in the output are 9, except the date field. All the date fields are showing up as 11 and I don't know how to resolve the issue:
Also,
the dates themselves, show up in Excel as Date-time, not Date, even though they are defined in the Database as a Date field. Converting them is also an issue. I cant seem to get rid of the Time portion.
Any help would be greatly appreciated. I have spent waay to much time on this.
Sounds to me like this problem.
If you have existing files, create a template excel file with in the correct format and use python to just fill the cells. (This scenario is the accepted answer in the post). You can also define a certain style in excel once and apply it to columns
Apparently, you have a somehow more complicated scenario. The second answer proposes to adjust the data in pandas before writing it to excel.
However, my personal guess is that it is rather formatting problem of excel so your approach seems reasonable. How about specifying the format explicitly: format = workbook.add_format({'num_format': 'yyyy-mm-dd'})? (Which youl rather align with this post. Try specifying the font height if setting the global font size does not work: 'height': 9*20 (note that you need to scale the height by 20 to use "points" as unit)

How to display (and format) datetime data in Qtableview with pyside2

I am trying to display datetime values in a QTableView. I have found this working pyside2 example (scroll down) for string and float type data:
PySide + QTableView example
What would I need to change within the table model so that I could display datetime data. How could this data be formatted to be displayed for example like '01.05.2019'.
I do NOT want to convert the datetime data to string beforehand since then the data cannot be sorted in a meaningful way when clicking in the table header...
Thanks a lot!
Just return the data as a QDateTime (or QDate or QTime). The QTableView should be fine with that.
If you want to format the date differently then it starts to get complicated: you'll need to convert it to a string using your own formatting. Then to get the sorting right, you'll need to return the original date data in some other role (Qt::UserRole) and set that to be the sort role, as explained in this answer (which also suggests an alternative approach using a delegate).

Modify column output for sqlform.grid() in Web2py

I have started using web2py for a web application and try to use SQLFORM.grid(...) to display a paginated listing of one of my db-table's data like in the following minimal example.
grid=SQLFORM.grid(query,
links=links,
fields=[db.example.date,db.example.foo, db.example.bar])
The db.example.date field contains a Python datetime.datetime object in UTC. At the moment it is displayed just plainly like that. However, I want to have more control about the actual output in a way that I can set the local timezone and modify the output string to have something like "2 hours ago".
As seen in another question[0] I can use the links to insert new columns. Unfortunately I can't seem to sort the rows by a field I have inserted in such way. Also, they are inserted on the right instead of actually replacing my first column. So that does not seem to be a solution.
To sum it up: How do I gain control about the way db.example.date is printed out in the end?
[0] Calculated Fields in web2py sqlgrid
You can achieve your goal when you define the table in your model. The represent parameter in the Field constructor that you used in define_table will be recognized by the SQLFORM.grid. For example, if you wanted to just print the date with the month name you could put the following in your model.
Field('a_date', type='date', represent=lambda x, row: x.strftime("%B %d, %Y")),
your function could also convert to local time.
You need to use prettydate to change the datetime arid format in a humanized string, and call it in the represent parameter of your Field() descriptor. For example :
from gluon.tools import prettydate
db.example.date.represent = lambda v,r: prettydate(r.date)
That way, any display of the db.example.date would be displayed humanized, including through SQLFORM.grid
If you don't want to have the date always represented in this way as per David Nehme's answer. Just before your grid creation, you can set the db.table.field.represent in the controller.
db.example.date.represent = lambda value, row: value.strftime("%B %d, %Y")
followed by.
grid = SQLFORM.grid(query,....
I use this often when I join tables. If there is a row.field in the represent from the model file it breaks because it then must be more specific, row.table.field.

Is it possible to specify Date XFStyle without an exact format with xlwt?

I'm using Python-Excel xlwt to create a blank Excel spreadsheet for filling out in a spreadsheet. I would like to specify that a certain range of cells should be date formatted. I'm doing something like:
datestyle = xlwt.XFStyle()
datestyle.num_format_str = "YYYY-MM-DD"
ws.write(row, column, "", datestyle)
but that's a bit over-prescriptive. People may be pasting in data, and that means that if the format doesn't match exactly then there will be problems. Spreadsheets are generally good at spotting and understanding dates pasted in in various formats. I want the spreadsheet to be able to do this without the restriction of a specific input format.
I just want to say 'this cell is a date' and not impose a format. Is this doable?
You can't specify that a cell is a date and not impose a format, not with xlwt and not with anything else, including Excel itself. Two reasons:
(1) You can't specify that a cell is any type. It is whatever the user types or pastes in. You can format it as a date but they can type in text.
(2) "date" is not a data type in Excel. All Excel knows about is text, floating point numbers, booleans (TRUE/FALSE), errors (#DIV/0 etc), and "blank" (formatting but no data). A date cell is just a number cell with a date format.
A general answer to "Can I do X with xlwt?" questions: Firstly try doing X with Excel / OpenOffice Calc / Gnumeric. If you can't, then neither can xlwt.
The format you're prescribing defines how the date will be displayed, but it won't affect how excel interprets entered dates. If your format is YYYY-MM-DD, the user can still enter 5/21/2008, and the string will be converted to it's date value (39589) and then displayed in your specified format: "2008-01-21"

Categories