Displaying one cell from a selected row using pyqt5 - python

im trying to create an UI with PyQt5 which has a tableWidget and a label that will display the text in every 4th column of the table, by order while the user scrolls through.
I cant seem to get the text in the selected cell from the table.. closest i got is this:
def open_csv_in_table (self):
f = open ("test.csv")
fData = csv.reader(f)
csvTable = list(fData)
self.tableWidget.setRowCount(len(csvTable))
self.tableWidget.setColumnCount(len(csvTable[0])-4)
for line in range( len(csvTable)):
for row in range(len(csvTable[0])):
self.tableWidget.setItem(line, row,QtWidgets.QTableWidgetItem(csvTable[line][row]))
self.tableWidget.setColumnWidth(0 , 10) # ID
self.tableWidget.setColumnWidth(1 , 150) # TEST NAME
self.tableWidget.setColumnWidth(2 , 50) # STATUS
self.tableWidget.setColumnWidth(3 , 300) # REMARKS
self.tableWidget.setColumnWidth(4 , 737) # LONG DESCRIPTION
def label_display(self):
self.label.setText(str(self.tableWidget.itemClicked))
print(str(self.tableWidget.itemClicked))
And im calling the display function with:
self.open_csv_in_table()
self.tableWidget.itemClicked.connect (lambda: self.label_display())

itemClicked is a signal that does not have the information of the item clicked so that is not the way to get that value. The signals what to do is pass the data through the arguments of the slot, in your case you must change to:
def label_display(self, item):
self.label.setText(item.text())
and
self.open_csv_in_table()
self.tableWidget.itemClicked.connect(self.label_display)

Related

PyQt5 : Get values from multiple QTextEdit obtained through loop

Currently working on a user interface through PyQt5, I'm trying to create TextEdit windows depending on the number selected from a Combobox (displayed in MainWindow).
This part is working (cf. first code below) however when I'm trying to get values (cf. second code) from text boxes created in the process, I only managed to get the value from the last text box.
Do you have any idea to get all of them?
Thanks in advance,
#Create text windows depending on number selected from a combo box
class Ui_SecondWindow(object):
def setupUi(self, SecondWindow):
_translate = QtCore.QCoreApplication.translate
SecondWindow.setObjectName("SecondWindow")
SecondWindow.resize(500, 720)
self.grid_layout = QtWidgets.QWidget(SecondWindow)
self.grid_layout.setGeometry(QtCore.QRect(0, 0, 250, 1000))
self.grid_layout.setObjectName("grid_layout")
self.grid = QtWidgets.QGridLayout(self.grid_layout)
self.grid.setContentsMargins(0,0,0,0)
self.grid.setObjectName('grid')
for i in range(1, int_nb_cond+1):
self.enter_nbcond = QtWidgets.QTextEdit(self.grid_layout)
self.enter_nbcond.setMaximumHeight(26)
self.enter_nbcond.setObjectName("enter_nbcond")
self.enter_nbcond.setPlaceholderText(_translate("SecondWindow", f"Name condition {i}:"))
self.enter_nbcond.resize(5,5)
self.grid.addWidget(self.enter_nbcond, i, 0)
#Get values from text edit windows
def ent(self):
print(self.enter_nbcond.toPlainText())
Standard rule: if you run for-loop then you have to keep results/items on list
Before loop you have to create list and inside loop you use .append() to keep widgets QTextEdit on this list.
# --- before loop ---
self.enter_nbcond = []
# --- loop ---
for i in range(1, int_nb_cond+1):
item = QtWidgets.QTextEdit(self.grid_layout)
item.setMaximumHeight(26)
item.setObjectName("enter_nbcond")
item.setPlaceholderText(_translate("SecondWindow", f"Name condition {i}:"))
item.resize(5,5)
self.grid.addWidget(item, i, 0)
self.enter_nbcond.append(item)
And later you have to use for-loop to get all values
def ent(self):
for item in self.enter_nbcond:
print(item.toPlainText())

.set in function is not being found in other function so it's creating an error tkinter python

I'm trying to create a GUI, in the nav menu you can click a cascade option to open another window where you can click roll to generate a set of numbers. It comes up with error. I think it's because the function is called from another function I just don't know how to get that function to call it/ if there is any other ways to fix this. I've tried global functions and looking it up but haven't found anything other than using classes so far, which I don't know how to do.
line 147, in totalRolls
txtresultsOut.set(totalRollResults)
NameError: name 'txtresultsOut' is not defined
Here is the code that is relevant to it. I've called the function to skip having to input all the other code for the main gui window.
def rollSix():
s = 0
numbers = [0,0,0,0]
for i in range(1,5):
numbers[s] = randrange(1,7)
s += 1
numbers.remove(min(numbers))
Result = sum(numbers)
totalRollResults.append(Result)
def totalRolls():
rollOne()
rollTwo()
rollThree()
rollFour()
rollFive()
rollSix()
txtresultsOut.set(totalRollResults)
def rollw():
rollWindow = tix.Tk()
rollWindow.title("Dice Rolls")
diceLabel = Label(rollWindow, text = "Click Roll for your Stats")
diceLabel.grid(row = 0, column = 0)
rollBtn = Button(rollWindow, text = "Roll Stats", command = totalRolls)
rollBtn.grid(row = 1, column = 0)
txtresultsOut = StringVar()
resultsOut = Entry(rollWindow, state = "readonly", textvariable = txtresultsOut)
resultsOut.grid(row = 2, column = 0)
rollw()
first of all I would NOT recommend using StringVar(). You can use the .get() method of Entry to obtain the value inside the same. Try this way and make a global declaration of the Entry whose values you want to get in other functions.
EDIT------------
#you can use the following code to make your entry active to be edited.
entry.configure(state='normal')
# insert new values after deleting old ones (down below)
entry.delete(0,END)
entry.insert(0, text_should_be_here)
# and finally make its state readonly to not let the user mess with the entry
entry.configure(state='readonly')

gtk.TreeView does not change after changing its gtk.ListStore:

Used: python 2.79, gtk 2.0
Dear python and PyGtk-users
In my program I want to give the opportunity to show searchresults of a great datafile in a gtk.TreeView using the method in the code. In the function that creates the ListStore I also create the csv-file the store is using. Now I can see, that the csv-file has changed after a new search with different keywords, but the TreeView does not, it still keeps the result of the first search, though I clear the store everytime self.search is running. It's really enerving if you need to restart the program for every new search...
I already tried some things, like creating a proper function for the datacreatin for the store, but nothing serves and the truth is that I don't have a lot of ideas...
And everything I found in the internet about this was about autorefreshing of the store with a timer or other topics more profound, seems like everyone instead of me knows how to do this...
Can anyone tell me, what mistake I am making? How do I refresh a TreeView?(as you can see self.search is called by a button...) here the relevant part of the code:
import gtk, csv
class BASE:
#...
#some other funtions, irrelevant for the problem
#...
def search(self, widget, event, data=None):
#...
#all the searchingstuff and the creation of 'inwrite.csv'
#...
with open('/home/emil/Documents/inwrite.csv', 'r') as storefile:
lines = storefile.readlines()
store = gtk.ListStore(str, str, str, str, str, str)
store.clear()
i=0
while i < len(lines):
line = [lines[i]]
csvfile = csv.reader(line, delimiter=',')
for row in csvfile:
temp = (row[0], row[1], row[2], row[3], row[4], row[5])
store.append(temp)
i = i + 1
self.tabview = gtk.TreeView(store)
self.tabview.set_rules_hint(True)
self.tabview.set_reorderable(True)
self.sw.add(self.tabview)
self.tabview.show()
self.create_columns(self.tabview)
def __init__(self):
#...
#creating the Window, entries,...
#...
self.button1 = gtk.Button('Buscar')
self.button1.connect('clicked', self.search, 'button 1')
#...
#packing and showing the whole GUI
#...
def create_columns(self, tabview):
rendererText = gtk.CellRendererText()
rendererText.props.wrap_width = 80
rendererText.props.wrap_mode = gtk.WRAP_WORD
column = gtk.TreeViewColumn('Codigo', rendererText, text=0)
column.set_sort_column_id(0)
self.tabview.append_column(column)
#...
#creating 5 more columns by the same principle
#...
def main(self):
gtk.main()
if __name__=='__main__':
base = BASE()
run = base
run.main()
thanks for your help, tell me if you need more information!
I do not know what is exactly wrong with your program (if you want to know that, you should provide a working minimal example).
Nevertheless, you do not need to manually update the TreeView because the TreeView always shows the content of the ListStore or TreeStore. You also do not have to create the ListStore everytime. You can create it one time and clear and insert the new entries when the event is emitted.
Here is a small example that shows how it works:
#from gi.repository import Gtk # uncomment to use PyGObject
import gtk as Gtk
class TestCase:
def __init__(self):
win = Gtk.Window()
button = Gtk.Button('Show')
button.connect('clicked', self.on_button_clicked)
self.clicked = 0
self.liststore = Gtk.ListStore(int)
self.liststore.append((self.clicked,))
view = Gtk.TreeView(self.liststore)
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn('demo', renderer, text=0)
view.append_column(column)
box = Gtk.HBox()
box.pack_start(button, True, True, 0)
box.pack_start(view, True, True, 0)
win.add(box)
win.connect('delete-event', Gtk.main_quit)
win.show_all()
def on_button_clicked(self, button):
self.clicked += 1
self.liststore.clear()
self.liststore.append((self.clicked,))
if __name__ == "__main__":
TestCase()
Gtk.main()
It also seems that you first create your csv file and read it afterwards. I don't know about the rest of your program but it is probably better to use the data directly and insert it into the ListStore and not read it from the csv file. It might be even possible then to just remove and insert the new entries and not clear the whole ListStore and insert everything again. That would be more efficient with bigger amounts of data.

Why Gtk.TreeSelection.select_iter() is not working?

I want to implement a feature which will allow user to navigate in Gtk.TreeView widget by arrow keys, unfortunately select_iter() method is not doing what I was expecting from it, i. e. it fails to select parent node of selected node :P
And now I need explanation why it's not working or hint on some kind of workaround of this issue.
Below is ready to run test program which demonstrates this problem. Problematic line of code is tagged with #FIXME.
from gi.repository import Gtk
from gi.repository import Gdk
class WizardManager(Gtk.Dialog):
'''Dialog window which makes possible to choose type of resource to create by editor.'''
def __init__(self, parent):
super().__init__('Wizard manager', parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT)
self.set_default_response(Gtk.ResponseType.OK)
self.set_decorated(False)
self.set_size_request(640, 480)
vbox = self.get_content_area()
self.__tree_store = Gtk.TreeStore(str)
self.__tree_view = Gtk.TreeView(self.__tree_store)
self.__tree_view.get_selection().set_mode(Gtk.SelectionMode.SINGLE)
self.__tree_view.connect('key-press-event', self.__on_tree_view_key_press)
self.__tree_view.set_headers_visible(False)
text_renderer = Gtk.CellRendererText()
text_column1 = Gtk.TreeViewColumn(None, text_renderer)
text_column1.add_attribute(text_renderer, 'text', 0)
self.__tree_view.append_column(text_column1)
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add(self.__tree_view)
vbox.pack_start(scrolled_window, True, True, 0)
self.__populate_tree_store()
self.show_all()
def __on_tree_view_key_press(self, tree_view, event):
# TODO Implement tree navigation with arrow keys
tree_selection = tree_view.get_selection()
selected_iter = tree_selection.get_selected()[1]
if selected_iter:
selected_tree_path = self.__tree_store.get_path(selected_iter)
# Right arrow and Return should expand selected node.
if event.keyval == Gdk.KEY_Right or event.keyval == Gdk.KEY_Return:
tree_view.expand_row(selected_tree_path, False)
# Left arrow should collapse node or select it parent.
elif event.keyval == Gdk.KEY_Left:
if not tree_view.collapse_row(selected_tree_path):
# Unable to collapse node it must be empty. select it's parent.
parent_iter = selected_iter.copy()
if self.__tree_store.iter_parent(parent_iter):
# FIXME Why select_iter() executes without error and is not able to select parent node?
# same goes for select_path() :P
tree_selection.select_iter(parent_iter)
def __populate_tree_store(self):
# Ordinary resources
self.__tree_store.append(None, ('File',))
self.__tree_store.append(None, ('Directory',))
# Python files
python_dir = self.__tree_store.append(None, ('Python',))
self.__tree_store.append(python_dir, ('Python module',))
self.__tree_store.append(python_dir, ('Python package',))
# Django files
django_dir = self.__tree_store.append(python_dir, ('Django',))
self.__tree_store.append(django_dir, ('Django project',))
self.__tree_store.append(django_dir, ('Django app',))
if __name__ == '__main__':
app = Gtk.Window(Gtk.WindowType.TOPLEVEL)
app.connect('destroy', lambda a: Gtk.main_quit())
dlg = WizardManager(app)
dlg.run()
dlg.destroy()
Gtk.main()
Here you have a hint!
#! /usr/bin/python
###########################################################
#
# Basic Gtk.TreeView Example with two sortable columns
#
###########################################################
# use the new PyGObject binding
from gi.repository import Gtk
import os
import getpass # this is only to automatically print your home folder.
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title='My Window Title')
self.connect('delete-event', Gtk.main_quit)
# Gtk.ListStore will hold data for the TreeView
# Only the first two columns will be displayed
# The third one is for sorting file sizes as numbers
store = Gtk.ListStore(str, str, long)
# Get the data - see below
self.populate_store(store)
treeview = Gtk.TreeView(model=store)
# The first TreeView column displays the data from
# the first ListStore column (text=0), which contains
# file names
renderer_1 = Gtk.CellRendererText()
column_1 = Gtk.TreeViewColumn('File Name', renderer_1, text=0)
# Calling set_sort_column_id makes the treeViewColumn sortable
# by clicking on its header. The column is sorted by
# the ListStore column index passed to it
# (in this case 0 - the first ListStore column)
column_1.set_sort_column_id(0)
treeview.append_column(column_1)
# xalign=1 right-aligns the file sizes in the second column
renderer_2 = Gtk.CellRendererText(xalign=1)
# text=1 pulls the data from the second ListStore column
# which contains filesizes in bytes formatted as strings
# with thousand separators
column_2 = Gtk.TreeViewColumn('Size in bytes', renderer_2, text=1)
# Mak the Treeview column sortable by the third ListStore column
# which contains the actual file sizes
column_2.set_sort_column_id(1)
treeview.append_column(column_2)
# Use ScrolledWindow to make the TreeView scrollable
# Otherwise the TreeView would expand to show all items
# Only allow vertical scrollbar
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.set_policy(
Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
scrolled_window.add(treeview)
scrolled_window.set_min_content_height(200)
self.add(scrolled_window)
self.show_all()
def populate_store(self, store):
directory = '/home/'+getpass.getuser()
for filename in os.listdir(directory):
size = os.path.getsize(os.path.join(directory, filename))
# the second element is displayed in the second TreeView column
# but that column is sorted by the third element
# so the file sizes are sorted as numbers, not as strings
store.append([filename, '{0:,}'.format(size), size])
# The main part:
win = MyWindow()
Gtk.main()

Python - Gtk.TreeView with CheckBox

I need to store items in a Gtk TreeView and when interacting with this TreeView, the user will can select one or more items in the list.
Because I'm new to GTK, I managed to populate the treeview and display a checkbox as the code below shows. But when I try to select, nothing happens and I do not know how to make this possible.
This is my Code:
# the column is created
renderer_products = gtk.CellRendererText()
column_products = gtk.TreeViewColumn("Products", renderer_products, text=0)
# and it is appended to the treeview
view.append_column(column_products)
# the column checkbox is created
renderer_checkbox = gtk.CellRendererToggle()
column_checkbox = gtk.TreeViewColumn("Selected", renderer_checkbox, text=0)
# and it is appended to the treeview
view.append_column(column_checkbox)
If you want to select the whole row and something happen:
#double click or not double click use
Gtk.TreeView.set_activate_on_single_click (bool)
#connect the treeview
treeview.connect ("row-activated", on_row_activate)
#inside the callback
def on_row_activate (treeview, path, column):
model = treeview.get_model ()
iter = treeview.get_iter (path)
yourdata = model[iter][model_index]
#do whatever with yourdata
If you want when you click the toggle and something happen:
#connect the renderer
renderer_checkbox.connect ("toggled", on_selected_toggled)
#inside the callback
def on_selected_toggled (renderer, path):
#modify the model or get the value or whatever

Categories