How can I get the text in QTableWidgetItem - pyqt4

I create a QWizard page, in the page, there is a QTableWidge include 4 rows and 6 cols, in each cell, I create a QTableWidge contains 2 rows and 1 col, we can input text to these small cells. Now I want to get all changed text before go to next page. What can I do? Thanks.
can not upload picture......

Use signals/slots to create a method that is run on when the following signal is emitted:
void QTableWidget::itemChanged ( QTableWidgetItem * item ) [signal]
with connect:
connect(tableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(on_table_item_changed(QTableWidgetItem*)));
Sorry about the formatting.

Related

I need help in Python with displaying the contents of a 2D Set into a Tkinter Textbox

Disclaimer: I have only begun to learn about Python. I took a crash course just to learn the very basics about a month ago and the rest of my efforts to learn have all been research thru Google and looking at solutions here in Stack Overflow.
I am trying to create an application that will read all PDF files stored in a folder and extract their filenames, page numbers, and the contents of the first page, and store this information into a 2D set. Once this is done, the application will create a tkinter GUI with 2 listboxes and 1 text box.
The application should display the PDF filenames in the first listbox, and the corresponding page numbers of each file in the second listbox. Both listboxes are synched in scrolling.
The text box should display the text contents on the first page of the PDF.
What I want to happen is that each time I click a PDF filename in the first listbox with the mouse or with up or down arrow keys, the application should display the contents of the first page of the selected file in the text box.
This is how my GUI looks and how it should function
https://i.stack.imgur.com/xrkvo.jpg
I have been successful in all other requirements so far except the part where when I select a filename in the first listbox, the contents of the first page of the PDF should be displayed in the text box.
Here is my code for populating the listboxes and text box. The contents of my 2D set pdfFiles is [['PDF1 filename', 'PDF1 total pages', 'PDF1 text content of first page'], ['PDF2 filename', 'PDF2 total pages', 'PDF2 text content of first page'], ... etc.
===========Setting the Listboxes and Textbox=========
scrollbar = Scrollbar(list_2)
scrollbar.pack(side=RIGHT, fill=Y)
list_1.config(yscrollcommand=scrollbar.set)
list_1.bind("<MouseWheel>", scrolllistbox2)
list_2.config(yscrollcommand=scrollbar.set)
list_2.bind("<MouseWheel>", scrolllistbox1)
txt_3 = tk.Text(my_window, font='Arial 10', wrap=WORD)
txt_3.place(relx=0.5, rely=0.12, relwidth=0.472, relheight=0.86)
scrollbar = Scrollbar(txt_3)
scrollbar.pack(side=RIGHT, fill=Y)
list_1.bind("<<ListboxSelect>>", CurSelect)
============Populating the Listboxes with the content of the 2D Set===
i = 0
while i < count:
list_1.insert(tk.END, pdfFiles[i][0])
list_2.insert(tk.END, pdfFiles[i][1])
i = i + 1
============Here is my code for CurSelect function========
def CurSelect(evt):
values = [list_1.get(idx) for idx in list_1.curselection()]
print(", ".join(values)) ????
========================
The print command above is just my test command to show that I have successfully extracted the selected item in the listbox. What I need now is to somehow link that information to its corresponding page content in my 2D list and display it in the text box.
Something like:
1) select the filename in the listbox
2) link the selected filename to the filenames stored in the pdfFilename 2D set
3) once filename is found, identify the corresponding text of the first page
4) display the text of the first page of the selected file in the text box
I hope I am making sense. Please help.
You don't need much to finish it. You just need some small things:
1. Get the selected item of your listbox:
selected_indexes = list_1.curselection()
first_selected = selected_indexes[0] # it's possible to select multiple items
2. Get the corresponding PDF text:
pdf_text = pdfFiles[first_selected][2]
3. Change the text of your Text widget: (from https://stackoverflow.com/a/20908371/8733066)
txt_3.delete("1.0", tk.END)
txt_3.insert(tk.END, pdf_text)
so replace your CurSelect(evt) method with this:
def CurSelect(evt):
selected_indexes = list_1.curselection()
first_selected = selected_indexes[0]
pdf_text = pdfFiles[first_selected][2]
txt_3.delete("1.0", tk.END)
txt_3.insert(tk.END, pdf_text)

QTableView: Prevent a user from navigating away from a spesific row

I am having trouble preventing the user form changing the current selection, if the save action did not complete successfully. I can re-select a row using the QTableView's selection models' currentRowChanged signal but although the selection change, the blue selection indicator does not. See the image below.
Example: In the image below the user attempted to add a new row nr 537. But the save action got an error and I don't want the user to navigate away from row 537 before the record is either deleted or edited and then saved
Question: How do I move the blue line to the current selection? (the current selection is the last row) (The QTableView's Selection Behavior is set to select rows)
Here is the code I got so far:
def __init__(self, parent):
...
self.__tableViewSelectionModel = self.__ui.tableView.selectionModel()
self.__tableViewSelectionModel.currentRowChanged.connect(self.rowChanged)
def rowChanged(self, current=None, previous=None):
if save() == True:
self.__ui.tableView.clearSelection()
self.__ui.tableView.selectRow(previous.row())
Replacing this:
self.__ui.tableView.clearSelection()
self.__ui.tableView.selectRow(previous.row())
with this:
QtCore.QTimer.singleShot(0.00001, lambda: self.__ui.tableView.selectRow(previous.row()))
produced the desired outcome

Python Docx Table row height

So column width is done using cell width on all cells in one column ike this:
from docx import Document
from docx.shared import Cm
file = /path/to/file/
doc = Document(file)
table = doc.add_table(4,2)
for cell in table.columns[0].cells:
cell.width = Cm(1.85)
however, the row height is done using rows, but I can't remember how I did it last week.
Now I managed to find a way to reference the rows in a table, but can't seem to get back to that way. It is possible to change the height by using the add_row method, but you can't create a table with no rows, so the the top row will always be the default height, which about 1.6cms.
There is a way to access paragraphs without using add_paragraph, does anyone know how to access the rows without using the add_row method because it was that that I used to set row height in a table as a default.
I have tried this but it doesn't work:
row = table.rows
row.height = Cm(0.7)
but although this does not give an error, it also has no effect on the height.
table.rows is a collection, in particular a sequence, so you need to access each row separately:
for row in table.rows:
row.height = Cm(0.7)
Also check out row.height_rule for some related behaviors you have access to:
https://python-docx.readthedocs.io/en/latest/api/table.html#row-objects
When you assign to table.rows.height, it just adds a .height instance attribute that does nothing. It's one of the side-effects of a dynamic language like Python that you encounter a mysterious behavior like this. It goes away as you gain more experience though, at least it has for me :)
Some additional information:
The answer here is correct, but this will give a minimum row height. Using WD_ROW_HEIGHT_RULE.EXACTLY will fix the cell height to the set row height ignoring the contents of the cell, this can result in cropping of the text in an undesirable way.
para = table.cell(0,0).add_paragrph('some text')
SOLUTION:
add_paragraph actually adds a blank line above the text.
Use the following instead to avoid using add_paragraph:
table.cell(0,0).paragraphs[0].text = 'some text'
or using add_run can make it easier to also work with the text:
run = table.cell(0,0).paragraphs[0].add_run('some text')
run.bold = True

Conditionally Color Table Cells with ReportLab

I've created a table using ReportLab. I would like to conditionally color the cells, depending on their contents (in my case, I want negative numbers to be red). To be clear, I have the conditional code working, I can't figure out how to add color. What I've tried:
using the <font color="..."> tag. Instead, the tags is included verbatim in the output.
wrapping each cell in Paragraph(...) (suggested in this answer). In this case, the cell text is linewrapped after each letter.
wrapping the table in Paragraph(...). In this case, reportlab errors out (I believe the resulting error was TypeError: split() missing required positional argument: 'availHeight')
I found reportlab.platypus.tables.CellStyle in the reportlab source code, but can't figure out make use of it. Google turns up nothing useful and it's not mentioned in the reportlab documentation.
I guess TableStyle(...) rules could be used, but the cells aren't in a predetermined position within the table (which is what all the examples assume).
Help appreciated!
Using TableStyle() would be an acceptable solution. You could loop through the data and add a style command when the condition is met.
Here is an example:
import random
from reportlab.lib.pagesizes import letter
from reportlab.lib.colors import red
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
# Generate random data with positive and negative values as list of lists.
data = []
for _ in range(20):
data.append(random.sample(range(-10, 10), 5))
table_style = TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT')])
# Loop through list of lists creating styles for cells with negative value.
for row, values, in enumerate(data):
for column, value in enumerate(values):
if value < 0:
table_style.add('TEXTCOLOR', (column, row), (column, row), red)
table = Table(data)
table.setStyle(table_style)
pdf = SimpleDocTemplate('example.pdf', pagesize=letter)
pdf.build([table])

Export right-to-left from RadGridView

I have a Silverlight application which has a RadGridView that is right to left.
when I export the grid, the result is left to right table.
I want the exported table would be in right to left format
(for example in Excel the sheet would be in right to left direction)
Edit not from OP to transfer clarification provided in comment
This picture is from the export result:
and this one is when I change sheet direction manually:
By adding some styling at the header part of your output in the export function, and for the Right-to-left alignment option it's inserted at the <WorksheetOptions> level of the declaration which called <x:DisplayRightToLeft/>.
Example if you're using C# in your project:
private string AddExcelStyling()
{
StringBuilder sb = new StringBuilder();
sb.Append("<html xmlns:o='urn:schemas-microsoft-com:office:office'\n" +
"xmlns:x='urn:schemas-microsoft-com:office:excel'\n" +
"xmlns='http://www.w3.org/TR/REC-html40'>\n" +
"<head>\n");
sb.Append("<style>\n");
sb.Append("#page");
sb.Append("mso-page-orientation:landscape;}\n");
sb.Append("</style>\n");
sb.Append("<!--[if gte mso 9]><xml>\n");
sb.Append("<x:ExcelWorkbook>\n");
sb.Append("<x:ExcelWorksheets>\n");
sb.Append("<x:ExcelWorksheet>\n");
sb.Append("<x:Name>Sheet Name</x:Name>\n");
sb.Append("<x:WorksheetOptions>\n");
sb.Append("<x:Print>\n");
sb.Append("<x:HorizontalResolution>600</x:HorizontalResolution\n");
sb.Append("<x:VerticalResolution>600</x:VerticalResolution\n");
sb.Append("</x:Print>\n");
sb.Append("<x:Selected/>\n");
sb.Append("<x:DisplayRightToLeft/>\n");
sb.Append("<x:DoNotDisplayGridlines/>\n");
sb.Append("</x:WorksheetOptions>\n");
sb.Append("</x:ExcelWorksheet>\n");
sb.Append("</x:ExcelWorksheets>\n");
sb.Append("</x:ExcelWorkbook>\n");
sb.Append("</xml><![endif]-->\n");
sb.Append("</head>\n");
sb.Append("<body>\n");
return sb.ToString();
}
See this link: http://forums.asp.net/p/1445619/3358464.aspx
I still have next to no idea of what is required, but here are some possibilities:
Starting with this:
sort ABC columns: Row / Sort by Row 1; Sort On Values; Order Largest to Smallest to get:
then click on Right-to-Left icon to get:
and sort again (same selection) to get this:
Stop when desired result is achieved.
Delete Row 1.
For code version click on Record Macro and repeat as many of above steps as required.
Stop recording.

Resources