Can one display rich text formatting in a QListWidget? - pyqt4

I have created a simple list using PyQt4:
class DeckList(QtGui.QListWidget):
def __init__(self, parent=None):
QtGui.QListWidget.__init__(self, parent)
for item in self.list:
self.addItem(item['title']+' '+item['description'])
Ideally I would like the list to display titles in bold and descriptions in italic.
Whereas a QLabel can take a string like "<b>title</b> <i>description</i>", a QListWidget item does not seem to render HTML tags in rich text.
Is there anyway to get this rich text to show?

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)

How can I get the values of my widget items to display in a TextArea and convert the values to dictionary

I am creating a post form that will send my input as dictionary to a server. I planned to display the user entered input in a TextArea with my first display button click. This display button sets the next button (Send) to be visible. The Send button then convert or saves the values to a dictionary (key/value pair).
In my code, i followed the example in the ipywidget documentation (https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Styling.html [cell 12]) by adding all my widgets in a list. I am have difficulty in calling the values of the widget items to display in the Text area
I have tried to access the values using children[0].values but get error each time. AttributeError: 'Button' object has no attribute 'values'. I will appreciate anyone's help to do this form. If i can get my inputs as a dictionary, that will be very helpful
from ipywidgets import Layout, Button, Box, FloatText, Textarea, Dropdown, Label, IntSlider, Text
#Form item layout
form_item_layout = Layout(
display='flex',
flex_flow='row',
justify_content='space-between'
)
#form container
form_items = [
Box([
Label(value='Name'),
Text(value='John')
], layout=form_item_layout),
Box([
Label(value='Collection UUID'),
Dropdown(options=['theme', 'play', 'character'])
], layout=form_item_layout),
Box([Label(value='Result'),
Textarea(rows = 20)], layout=form_item_layout),
Button(description="display"),
Button(description="Send", button_style='success')
]
#box layout that holds the forms
box_lyt = Layout(
display='flex',
flex_flow='column',
border='solid 2px',
align_items='stretch',
width='50%'
)
form = Box(children=form_items, layout=box_lyt)
display(form)
form.children[4].layout.visibility = 'hidden'
def show(b):
form.children[4].layout.visibility = 'visible'
form.children[2] = c.children[0] + c.children[1] + c.children[2]
#Convert textarea values to dictionary
def list_children(c):
return c.children[2].to_dict()
form.children[3].on_click(show)
form.children[4].on_click(list_children )
I expect a widget displaying: Name, ID, result and display button. Clicking the display should show the values in the result TextArea and make the button (send) visible. Clicking the Send button should accept these values from result and save as dictionary. The widget displays but is not responsiveenter image description here

How to prevent a closing tab QTabWidget? PyQT4

With this code:
QtCore.QObject.connect(self.tabWidget, QtCore.SIGNAL("tabCloseRequested(int)"),
self.tabWidget.removeTab)
I can close any tab QTabWidget, and the names of these tabs are:
work_1
work_2
work_3
But I want the tab work_1 never closes.
Use Index did not work for two reasons:
The tabs can be dynamically moved by this code:
self.tabWidget.setMovable (True)
That makes the Index are constantly changing.
The user has the ability to add new tabs.
Tabs can be identified by their widgets, and the widgets can be identified by their objectName (or some other unique attribute):
self.tabWidget.tabCloseRequested.connect(sef.removeTab)
...
def removeTab(self, index):
widget = self.tabWidget.widget(index)
if widget is not None and widget.objectName() != 'work_1':
self.tabWidget.removeTab(index)
or perhaps more simply:
if widget is not None and widget is not self.work_1:
self.tabWidget.removeTab(index)

QScrollArea won't scroll

I am trying to put a QtableWidget inside a QScrollArea (only one widget) to be able to scroll it vertically and horizontaly (I have reasons not to use scrollbars in Qtablewidget ). However, no scrollbar appears even though the tableWidget can’t fit inside the window so I set QtCore.Qt.ScrollBarAlwaysOn, and now they are there but they are gray and still I can't scroll.
Here is my code:
class Table(QtGui.QDialog):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
layout = QtGui.QGridLayout()
tableWidget = QtGui.QTableWidget()
#.... set up and populate tableWidget here 1000rows-10col ....
myScrollArea = QtGui.QScrollArea()
myScrollArea.setWidgetResizable(True)
myScrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
myScrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
myScrollArea.setWidget(tableWidget)
layout.addWidget(myScrollArea)
self.setLayout(layout)
self.setMinimumSize(1000, 700)
I am begginer with PyQt and I don't really understand layouts and containers, so I can't figure out what I'm doing wrong. Please point me in right direction, help would be appreciated.
QtScrollBar by default has horizontal and vertical scrollBar.
tablewidget by default has horizontal and vertical scrollBar. so i have made it off.
just using the resize event i have resized width and height of tablewidget.
class MainWin(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.table =QtGui.QTableWidget(100,4)
self.table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
lay = QtGui.QGridLayout()
self.sc = QtGui.QScrollArea()
self.sc.setWidget(self.table)
lay.addWidget(self.sc,0,0)
self.setLayout(lay)
def resizeEvent(self,event):
self.table.resize(self.sc.width(),self.sc.height())
def main():
app=QtGui.QApplication(sys.argv)
win=MainWin()
win.show()
sys.exit(app.exec_())
main()
I finally get it:
I've used resizeColumnsToContents() and resizeRowsToContents() to make the columns/rows of the table adjust to the data - text, but that doesn't do the same thing with the Table itself - table height and width stays the same. So in order to make table to be sized around the rows and columns I've used this:
self.table.resizeRowsToContents()
self.table.resizeColumnsToContents()
self.table.setFixedSize(self.table.horizontalHeader().length(), self.table.verticalHeader().length())
and now I can scroll with QScrollArea's scrollbars through entire table.

Tkinter insert a Combobox inside a Treeview widget

For example, lets create a Treeview widget using a class as follows:
class FiltersTree:
def __init__(self, master, filters):
self.master = master
self.filters = filters
self.treeFrame = Frame(self.master)
self.treeFrame.pack()
self._create_treeview()
self._populate_root()
def _create_treeview(self):
self.dataCols = ['filter', 'attribute']
self.tree = ttk.Treeview(self.master, columns = self.dataCols, displaycolumns = '#all')
Populate root, insert children as usual. At the end of the codeblock, you can see where I want to put a Combobox in the tree, using a Combo object:
def _populate_root(self):
# a Filter object
for filter in self.filters:
top_node = self.tree.insert('', 'end', text=filter.name)
# a Field object
for field in filter.fields:
mid_node = self.tree.insert(top_node, 'end', text = field.name)
# insert field attributes
self.insert_children(mid_node, field)
def insert_children(self, parent, field):
name = self.tree.insert(parent, 'end', text = 'Field name:',
values = [field.name])
self.tree.insert(parent, 'end', text = 'Velocity: ',
values = [Combo(self)]) # <--- Combo object
...
Next the class definition of Combo follows. The way I understand it, the combobox widget inherits from and must be placed inside the Labelframe widget from ttk:
class Combo(ttk.Frame):
def __init__(self, master):
self.opts = ('opt1', 'opt2', 'etc')
self.comboFrame = ttk.Labelframe(master, text = 'Choose option')
self.comboFrame.pack()
self.combo = ttk.Combobox(comboFrame, values=self.opts, state='readonly')
self.combo.current(1)
self.combo.pack()
So is this completely wrong? I want to have the ability to change between units (eg m/s, ft/s, etc) from within the Treeview widget.
Any suggestions, plz?
The treeview widget doesn't support embedded widgets. The values for the values attribute are treated as strings.
By default, a Treeview is a static display of a forest of lists of strings. However, with work, after carefully reading Treeview references, one can make a Treeview fairly interactive. For this question, I would bind left click to an event handler that compares the mouse x,y to the bounding box (.bbox) for the units attribute cell. If in the box, display a Combobox, initialized with the current value (such as 'flops'), directly on top of the units attribute cell.
Tkinter.ttk Treeview reference and Tcl/tk treeview reference
Of course, it might be easier to put the Treeview in a frame with with a separate Combobox.

Resources