How to get index of a cell in QTableWidget? - python

I created a table widget and added a contextmenu to it. When I right click the cell,I want to get a file directory and put it into the cell. I've got the directory and pass it to a variable, but i failed to display it in the cell,because I can't get the index of the cell.How to get index of a cell in QTableWidget? Is there any orther method to figure out this qusstion? I'm using Python and PyQt5.
enter image description here
#pyqtSlot()
def on_actionAddFolder_triggered(self):
# TODO: Open filedialog and get directory
filedir = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
return filedir
#pyqtSlot(QPoint)
def on_tableWidget_customContextMenuRequested(self, pos):
# TODO: get directory and display it in the cell
x = self.tableWidget.currentRow
y = self.tableWidget.currentColumn
RightClickMenu = QMenu()
AddFolder = RightClickMenu.addAction('Add Folder')
FolderAction = RightClickMenu.exec_(self.tableWidget.mapToGlobal(pos))
if FolderAction == AddFolder:
NewItem = QTableWidgetItem(self.on_actionAddFolder_triggered())
self.tableWidget.setItem(x,y, NewItem)

hahaha, I find the mistake!
x = self.tableWidget.currentRow
y = self.tableWidget.currentColumn
replace these two lines
x = self.tableWidget.currentRow()
y = self.tableWidget.currentColumn()
then it works.

Related

How can I select an item from a tkinter listbox?

The inp_list is a listbox. I wish to select the first item from that list. I tried to use inp_list.get(0) and alsoinp_list.select_set(0) but I get this error: _tkinter.TclError: invalid command name ".!listbox".
How can I choose it? (the problematic line is marked with ***)
def add_inp_func(inp_list):
inp_file = filedialog.askopenfile(mode='r', filetypes=[("Input files", '*.inp')])
if inp_file is not None:
inp_list.insert(END, utils.getFileNameWithoutBackSlash(inp_file.name))
def save_inp_func(inp_list,add_inp_window,table_frame):
#first_one = 0
for j in enumerate(inp_dict):
# if first_one == 0:
# first_one=1
# continue
del inp_dict[j]
i =1
for listbox_entry in inp_list.get(0, END):
inp_dict[i] =listbox_entry
i+=1
add_inp_window.destroy()
if inp_list:
erase_widgets()
inp_file = inp_dict[1]
if inp_file is not None: # in case someone presses the browse and doesnt choose anything
***working_dir = utils.getFolderPath(inp_list.get(0) ) # get path to the working*** directory
slashed_work_dir = utils.convertBackSlash(working_dir) ```

On_click event on a TwoLineIconListItem in kivy

I have an array of values . I have to show this list in a TwoLineIconListItem in kivy along with an image icon and with other information in a list view. When the user clicks on any of the list item, a popup should come (preferably a dialog) and I have to show the item text selected...Pls do help !!
I could write everything but it seems like I am unable to pass the value to the dialog from my TwoLineIconListItem...the code snippet is here where I need some help to achieve this please...
while counter < len(list_of_names):
self.party_name = list_of_names[counter]
self.party_pic = IconLeftWidget(icon=image_source + "\\" + list_of_names[counter].lower() + ".png")
counter += 1
items = TwoLineIconListItem(text=str(counter) + " : " + self.party_name,
secondary_text=self.party_name_details,
on_release=self.select_item)
items.add_widget(self.party_pic)
list_view.add_widget(items)
screen.add_widget(scroll)
return screen
def select_item(self, obj):
print(obj)
# It's should print the item text selected
close_btn = MDFlatButton(text="Close", on_release=self.close_dialog)
confirm_btn = MDFlatButton(text="I Confirm !", on_release=self.confirm_choice)
self.dialog = MDDialog(title="Please confirm your choice!",
text=self.party_name,
size_hint=(0.7, 1),
buttons=[close_btn, confirm_btn]
)
self.dialog.open()

How to create a Gtk3 Entry in Python not editable but receive Drag and Drop?

I created a Gtk.Entry with Drag and Drop function. This entry is able to receive text data from Drag and Drop.
But change text by hand should not be allowed, so I set editable to False.
Now Drag and Drop is no longer working. Method "on_drag_data_received" is no longer called.
Searching for a solution...
class DragDropEntry(Gtk.Entry):
def __init__(self, placeholder_text="drop something here", editable=False):
Gtk.Entry.__init__(self, placeholder_text=placeholder_text, editable=editable)
self.drag_dest_set(Gtk.DestDefaults.ALL, [], DRAG_ACTION)
self.connect("drag-data-received", self.on_drag_data_received)
self.drag_dest_add_text_targets()
def on_drag_data_received(self, widget, drag_context, x, y, data, info, time):
uri = data.get_data().strip('\r\n\x00')
uri_splitted = uri.split() # we may have more than one file dropped
for uri in uri_splitted:
path = self.get_file_path_from_dnd_dropped_uri(uri)
self.set_text(path)
return
def get_file_path_from_dnd_dropped_uri(self, uri):
path = ""
if uri.startswith('file:\\\\\\'): # windows
path = uri[8:] # 8 is len('file:///')
elif uri.startswith('file://'): # nautilus, rox
path = uri[7:] # 7 is len('file://')
elif uri.startswith('file:'): # xffm
path = uri[5:] # 5 is len('file:')
path = urllib.url2pathname(path) # escape special chars
path = path.strip('\r\n\x00') # remove \r\n and NULL
return path

How to continuously change an image using the value of a tkinter Scale widget

I have a bunch of images which I want the user to select using a scale. As the user updates the scale value, I want the GUI to update which image is shown.
I have just started dealing with GUIs and I'm stuck. I've managed to print the new values from the scale using the command keyword argument of the Scale widget. However, it is not clear how I can get this value to update the image on the interface.
class MainProgram():
def AcquireDicomFiles(self):
# HERE I GET THE IMAGES PATHS. IT WORKS FINE.
def GUI(self):
root_window = Tk()
slice_number = DoubleVar()
bar_length = 200
main_title = Label(root_window, text="Seleção de corte e echo").pack()
scale_slice = Scale(root_window, variable=slice_number, orient=HORIZONTAL, from_=1, to=24, length=bar_length,
cursor="hand", label="Slice Number", command=MainProgram().get_slice_value)
scale_slice.pack(anchor=CENTER)
echo_time = DoubleVar()
scale_echo = Scale(root_window, variable=echo_time, orient=HORIZONTAL, from_=1, to=6, length=bar_length,
cursor="hand", label="Echo Time")
scale_echo.pack(anchor=CENTER)
imagefile = Image.open("image.png")
tk_image = ImageTk.PhotoImage(imagefile)
panel = Label(root_window, image=tk_image).pack(fill="both", expand="yes")
root_window.mainloop()
def get_slice_number(self,user_slice_number):
user_slice_number = np.int(user_slice_number)
def showImage(self):
# Code below works fine for user input in terminal. It uses user_slice_number and user_echo_time to find image. I want these two values to come from the pair of scales
# indexes = np.where(slice_and_echo[:][0] == user_slice_number)[0] #indexes of the elements where the user input match the element
# for i in indexes: #Go through index values. Check and record those in which echo time (element) matches user input
# if slice_and_echo[i][1] == user_echo_time:
# selected_echo_time = user_echo_time
# selected_slice_number = slice_and_echo[i][0]
# index = i
# file_path = os.path.join(dcm_folder, dcm_files[index]) #path of the file whose index match user input
# dcm_read = dicom.read_file(file_path) #read file user wants
# dcm_pixel_values = dcm_read.pixel_array #extract pixel values
slice_and_echo = MainProgram().AcquireDicomFiles()
MainProgram().GUI()
Set echo_time.trace(slider_callback), (which calls the method given to it, whenever the echo_time changes value) and then within slider_callback, you set root_window.iconify(file_name).

Adding items from one listbox to another with tkinter

As the title implies I'm trying to select items from one list box, press a button, and add it to a second list box.
When I click the button to move, the value is printed in command prompt, but the listbox itself isn't updating.
I copied and pasted so I realize that everything should be tabbed over one spot.
class Actions:
def openfile(self): #select a directory to view files
directory = tkFileDialog.askdirectory(initialdir='.')
self.directoryContents(directory)
def filename(self):
Label (text='Please select a directory').pack(side=TOP,padx=10,pady=10)
files = []
fileListSorted = []
#display the contents of the directory
def directoryContents(self, directory): #displays two listBoxes containing items
scrollbar = Scrollbar() #left scrollbar - display contents in directory
scrollbar.pack(side = LEFT, fill = Y)
scrollbarSorted = Scrollbar() #right scrollbar - display sorted files
scrollbarSorted.pack(side = RIGHT, fill = Y, padx = 2, pady=100)
fileList = Listbox(yscrollcommand = scrollbar.set) #files displayed in the left listBox
for filename in os.listdir(directory):
fileList.insert(END, filename)
global files
self.files.append(filename) #insert the values into the files array so we know which element we want to enter in moveFile
fileList.pack(side =LEFT, fill = BOTH)
scrollbar.config(command = fileList.yview)
global fileListSorted #this is for the filelist in the right window. contains the values the user has selected
fileListSorted = Listbox(yscrollcommand = scrollbarSorted.set) #second listbox (button will send selected files to this window)
fileListSorted.pack(side=RIGHT, fill = BOTH)
scrollbarSorted.config(command = fileListSorted.yview)
selection = fileList.curselection() #select the file
b = Button(text="->", command=lambda:self.moveFile(fileList.curselection()))#send the file to moveFile to be added to fileListSorted
b.pack(pady=5, padx =20)
##moveFile addes files to the array fileLIst2, which is the fileList on the right
def moveFile(self,File):
insertValue = int(File[0]) #convert the item to integer
global files
insertName = self.files[insertValue] #get the name of the file to be inserted
global fileListSorted
self.fileListSorted.append(str(insertName)) #append the value to the fileList array
print self.fileListSorted #second listbox list
It's quite difficult to follow that code -- For example, where is self.fileListSorted defined? -- You have a global fileListSorted and an instance variable self.fileListSorted and they're different things. However, you seem to be getting them confused (for example, why is there a line
global fileListSorted
in moveFile when you never use fileListSorted in there?) Also note that to add items into a ListBox, you typically use the insert method, which you haven't used in moveFiles as far as you've shown anyway...

Categories

Resources