I want to create an auto-complete TextField.
I mean - when you type something in the field and see a prompt list below. The prompt list is an array with possible values. The best way to explain it show a similar picture.
I already have some experience in Pythonista 3 but it was not UI programming experience.
I understand this is complex and that maybe I should use an additional View and Delegate mechanism but I don't have any idea how to start. I have already spent several days in Google looking for a solution, but I can't, in the context of Pythonista.
Has anybody done this? Or could someone provide useful links for reading?
A drop-down list can be created in Pythonista using a TableView. TableViews are really just single-column lists, they’re not just for tables.
So the steps would be:
Create a tableview.
Align it with your text field.
Hide the tableview until typing starts.
Update the tableview’s item list with the auto-completion options whenever the typing changes.
Potentially hide the tableview again when typing ends.
You can hide any view by setting its .hidden property to True.
You can do things when typing starts in a TextField by creating a delegate object that implements textfield_did_change.
You set a TableView to have a list of items by giving the TableView a data_source, probably an implementation of ui.ListDataSource. Whenever the items property on the data source changes, the list of options will also automatically change.
You can react to the user choosing an option from the TableView by setting an action on the TableView’s delegate.
The documentation for TableView, TextField, ListDataSource, delegates, and actions, can be found at Pythonista’s Native GUI for iOS documentation.
Here is a basic example:
# documentation at http://omz-software.com/pythonista/docs/ios/ui.html
import ui
# the phoneField delegate will respond whenever there is typing
# the delegate object will combine phoneField delegate, tableview delegate, and data source, so that it can share data
class AutoCompleter(ui.ListDataSource):
def textfield_did_change(self, textfield):
dropDown.hidden = False
# an arbitrary list of autocomplete options
# you will have a function that creates this list
options = [textfield.text + x for x in textfield.text]
# setting the items property automatically updates the list
self.items = options
# size the dropdown for up to five options
dropDown.height = min(dropDown.row_height * len(options), 5*dropDown.row_height)
def textfield_did_end_editing(self, textfield):
#done editing, so hide and clear the dropdown
dropDown.hidden = True
self.items = []
# this is also where you might act on the entered data
pass
def optionWasSelected(self, sender):
phoneField.text = self.items[self.selected_row]
phoneField.end_editing()
autocompleter = AutoCompleter(items=[])
autocompleter.action = autocompleter.optionWasSelected
# a TextField for phone number input
phoneField = ui.TextField()
phoneField.delegate = autocompleter
phoneField.keyboard_type = ui.KEYBOARD_PHONE_PAD
phoneField.clear_button_mode = 'while_editing'
# the drop-down menu is basically a list of items, which in Pythonista is a TableView
dropDown = ui.TableView()
dropDown.delegate = autocompleter
dropDown.data_source = autocompleter
# hide the dropdown until typing starts
dropDown.hidden = True
# create interface
mainView = ui.View()
mainView.add_subview(phoneField)
mainView.add_subview(dropDown)
# present the interface before aligning fields, so as to have the window size available
mainView.present()
# center text field
phoneField.width = mainView.width*.67
phoneField.height = 40
phoneField.x = mainView.width/2 - phoneField.width/2
phoneField.y = mainView.height/3 - phoneField.height/2
# align the dropdown with the phoneField
dropDown.x = phoneField.x
dropDown.y = phoneField.y + phoneField.height
dropDown.width = phoneField.width
dropDown.row_height = phoneField.height
On my iPhone, this code creates an interface that looks like this:
Related
I'm working on something that gets and stores the transforms of an object moved by the user and then allows the user to click a button to return to the values set by the user.
So far, I have figured out how to get the attribute, and set it. However, I can only get and set once. Is there a way to do this multiple times within the script running once? Or do I have to keep rerunning the script? This is a vital question for me get crystal clear.
basically:
btn1 = button(label="Get x Shape", parent = layout, command ='GetPressed()')
btn2 = button(label="Set x Shape", parent = layout, command ='SetPressed()')
def GetPressed():
print gx #to see value
gx = PyNode( 'object').tx.get() #to get the attr
def SetPressed():
PyNode('object').tx.set(gx) #set the attr???
I'm not 100% on how to do this correctly, or if I'm going the right way?
Thanks
You aren't passing the variable gx so SetPressed() will fail if you run it as written(it might work sporadically if you tried executing the gx = ... line directly in the listener before running the whole thing -- but it's going to be erratic). You'll need to provide a value in your SetPressed() function so the set operation has something to work with.
As an aside, using string names to invoke your button functions isn't a good way to go -- you code will work when executed from the listener but will not work if bundled into a function: when you use a string name for the functions Maya will only find them if they live the the global namespace -- that's where your listener commands go but it's hard to reach from other functions.
Here's a minimal example of how to do this by keeping all of the functions and variables inside another function:
import maya.cmds as cmds
import pymel.core as pm
def example_window():
# make the UI
with pm.window(title = 'example') as w:
with pm.rowLayout(nc =3 ) as cs:
field = pm.floatFieldGrp(label = 'value', nf=3)
get_button = pm.button('get')
set_button = pm.button('set')
# define these after the UI is made, so they inherit the names
# of the UI elements
def get_command(_):
sel = pm.ls(sl=True)
if not sel:
cmds.warning("nothing selected")
return
value = sel[0].t.get() + [0]
pm.floatFieldGrp(field, e=True, v1= value[0], v2 = value[1], v3 = value[2])
def set_command(_):
sel = pm.ls(sl=True)
if not sel:
cmds.warning("nothing selected")
return
value = pm.floatFieldGrp(field, q=True, v=True)
sel[0].t.set(value[:3])
# edit the existing UI to attech the commands. They'll remember the UI pieces they
# are connected to
pm.button(get_button, e=True, command = get_command)
pm.button(set_button, e=True, command = set_command)
w.show()
#open the window
example_window()
In general, it's this kind of thing that is the trickiest bit in doing Maya GUI -- you need to make sure that all the functions and handlers etc see each other and can share information. In this example the function shares the info by defining the handlers after the UI exists, so they can inherit the names of the UI pieces and know what to work on. There are other ways to do this (Classes are the most sophisticated and complex) but this is the minimalist way to do it. There's a deeper dive on how to do this here
I would like to create a hover box (or info box) which opens up when the user places the mouse cursor on top of a Pmw RadioSelect label. For example, when the cursor is placed on top of "Primary" the program opens an info box explaining what "Primary" means.
Problem: I don't know how to access the individual labels inside the RadioSelect object. I need to bind a method to the individual labels, but I don't know how to refer to them.
Extra: How could I have solved this myself? I tried looking at the RadioSelect attributes with dir() and I read the Pmw manual online, but couldn't find the information.
EDIT This is what I have found out thus far: The manual says that the labels only start to exist if their position is set explicitly:
labelpos
Initialisation option. Specifies where to place the label component.
If None, a label component is not created. The default is None
After setting it explicitly for example as so:
self.rs = Pmw.RadioSelect(parent, labelpos = 'w')
you can refer to it with
self.rs.component('label')
But I still don't know how to reach the individual labels.
EDIT 2: The trick was just to assign the RadioSelect "items" into variables like the accepted answer suggests:
self.cb1 = self.radio_select.add("text")
After assigning the "item" into a variable you can simply bind methods to the variable, like such:
self.balloon = Pmw.Balloon(self, initwait=500, relmouse='both')
self.balloon.bind(self.cb1, "Balloon text example")
If I understand well your problem, I think you are looking for:
To rely on Pmw to draw the widgets (unlike what I did with Tkinter previously)
when the cursor is placed on top of "Primary" the program opens an info box explaining what "Primary" means. (the effect I produced on the demo below)
Identify individual checkbuttons (or what you call in your own terms reaching the individual labels within the Pmw.RadioSelect)
Solution:
The solution for the first problem you know it already.
For the second problem, as I explained previously, you will need to instantiate Pmw.Balloon() and bind it to individual checkbuttons (or labels as you call them). I re-programmed that as you can see below but using an other method. I mean I relied mainly on add() which returns the component widget. Then I binded the instance of Pmw.Balloon() to the returned value from add(). Doing this, you already offer yourself a way to access individually the checkbuttons (and you play more with this if you want)
You can access individual checkbuttons (labels) by using getvalue() or getcurselection() methods which work similarly by returning the return the name of the currently selected button. But in practice, you will get tuples ( I mean these functions return the names of all selected checkbuttons, as I showed in the access_to_labels_individually() that I used as a callback method to display the names of the checkbuttons you select; of course you can play with that also depending on your needs)
Code
Here is an MVCE program:
'''
Created on Jun 18, 2016
#author: Billal BEGUERADJ
'''
# -*- coding: utf-8 -*-
import Pmw
import tkinter as tk
class Begueradj:
def __init__(self, parent):
self.balloon = Pmw.Balloon(parent)
# Create and pack a vertical RadioSelect widget, with checkbuttons.
self.checkbuttons = Pmw.RadioSelect(parent,
buttontype = 'checkbutton',
orient = 'vertical',
labelpos = 'w',
command = self.access_to_labels_individually,
hull_borderwidth = 2,
hull_relief = 'ridge',
)
self.checkbuttons.pack(side = 'left', expand = 1, padx = 10, pady = 10)
# Add some buttons to the checkbutton RadioSelect
self.cb1 = self.checkbuttons.add('Primary')
self.cb2 = self.checkbuttons.add('Secondary')
self.cb3 = self.checkbuttons.add('Tertiary')
# Bind the Balloon instance to each widget
self.balloon.bind(self.cb1, 'Primary:\n This is our primary service')
self.balloon.bind(self.cb2, 'Secondary:\n This is our primary service')
self.balloon.bind(self.cb3, 'Tertiary:\n This is our primary service')
# You can use getvalue() or getcurselection() to access individual labels
def access_to_labels_individually(self, tag, state):
print(self.checkbuttons.getvalue())
# Main program starts here
if __name__ =='__main__':
begueradj = Pmw.initialise(fontScheme = 'pmw1')
begueradj.title('Billal BEGUERADJ')
d = Begueradj(begueradj)
begueradj.mainloop()
Demo
(I am keeping the same screenshots because the above program produces the same results)
Here are screenshots of the running program related to the mouse hovering over each tkinter.Checkbutton() instance whether it is selected or not:
I want both view below are blue, how to set it? please help me! when i forcus to the second line i want it highlight both of object are blue, not one blue and one grey as below.
Code like this:
ui = twin_gtk_builder('twin.ui', ['dia_support', 'liststore7'])
win = ui.get_object('dia_support')
##### Begin function tree view
liststore = gtk.ListStore(int, int, int)
liststore.append([1,2,3])
liststore.append([2,2,2])
liststore.append([4,4,4])
win.sw = gtk.ScrolledWindow()
win.sm = gtk.TreeModelSort(liststore)
##### Set sort column
n = 1
win.sm.set_sort_column_id(n, gtk.SORT_ASCENDING)
win.tv = gtk.TreeView(win.sm)
win.vbox.pack_start(win.sw)
win.sw.add(win.tv)
win.tv.column = [None] * 3
win.tv.column[0] = gtk.TreeViewColumn('0-1000')
win.tv.column[1] = gtk.TreeViewColumn('0-1000000')
win.tv.column[2] = gtk.TreeViewColumn('-10000-10000')
win.tv.cell = [None] * 3
for i in range(3):
win.tv.cell[i] = gtk.CellRendererText()
win.tv.append_column(win.tv.column[i])
win.tv.column[i].set_sort_column_id(i)
win.tv.column[i].pack_start(win.tv.cell[i], True)
win.tv.column[i].set_attributes(win.tv.cell[i], text=i)
##### End function tree view
win.show_all()
and how it work
Tried one more time with #PM 2Ring help, Thanks so much for your help!
Somebody did it like this, but i can't find his contact...
I had to do a bit of work to get that code to run, Sunshine jp. In future, please try to post code that others can run & test, especially if it's GUI code. Otherwise it can be very hard to work out what the problem is and how to fix it.
I'm not familiar with twin_gtk1_builder(). Is it a GTK1 function?
Anyway, I've modified your code to run on GTK2+. I'm not quite sure what you want your code to do. So I've given row 2 a background color of cyan. Also, I've added the ability to make multiple selections, either using Ctrl or Shift on the keyboard when you select with the mouse; you can also do multiple selection with the keyboard with shift up and down arrows.
When the window loses focus the selected row(s) stays blue on my system. Maybe that's a feature of GTK2 that GTK1 doesn't have. (Or maybe it's due to my window manager - I'm using KDE 4.5.3 on Mepis Linux).
#!/usr/bin/env python
'''
TreeView test
From http://stackoverflow.com/questions/25840091/how-to-make-forcus-highlight-for-2-objects-at-the-same-time
'''
import pygtk
#pygtk.require('2.0')
import gtk
def TreeViewTest():
def delete_event(widget, event, data=None):
gtk.main_quit()
return False
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.set_title("TreeView Test")
win.set_size_request(320, 160)
win.connect("delete_event", delete_event)
win.vbox = gtk.VBox()
win.add(win.vbox)
win.sw = gtk.ScrolledWindow()
win.vbox.pack_start(win.sw)
##### Begin function tree view
#Set up liststore data. Column 3 controls whether
# background color of the TreeView is default or special.
liststore = gtk.ListStore(int, int, int, bool)
liststore.append([1, 2, 3, False])
#Tell row 2 to use the special color
liststore.append([2, 2, 2, True])
liststore.append([4, 4, 4, False])
win.sm = gtk.TreeModelSort(liststore)
##### Set initial sort column
n = 1
win.sm.set_sort_column_id(n, gtk.SORT_ASCENDING)
win.tv = gtk.TreeView(win.sm)
win.sw.add(win.tv)
win.tv.column = [None] * 3
win.tv.column[0] = gtk.TreeViewColumn('0-1000')
win.tv.column[1] = gtk.TreeViewColumn('0-1000000')
win.tv.column[2] = gtk.TreeViewColumn('-10000-10000')
#Set up cell renderers
win.tv.cell = [None] * 3
for i in range(3):
win.tv.cell[i] = gtk.CellRendererText()
win.tv.cell[i].set_property('cell-background', 'cyan')
win.tv.append_column(win.tv.column[i])
win.tv.column[i].set_sort_column_id(i)
win.tv.column[i].pack_start(win.tv.cell[i], True)
#win.tv.column[i].set_attributes(win.tv.cell[i], text=i)
win.tv.column[i].set_attributes(win.tv.cell[i], text=i,
cell_background_set=3)
#Allow multiple selection
treeselection = win.tv.get_selection()
treeselection.set_mode(gtk.SELECTION_MULTIPLE)
##### End function tree view
win.show_all()
def main():
TreeViewTest()
gtk.main()
if __name__ == "__main__":
main()
Note that this is NOT a good way to make a GUI. You should be creating a proper class, not adding everything as an attribute to win. Please see the PyGTK 2.0 Tutorial for plenty of code examples.
Edit
Ok. Sorry about my earlier confusion over what your problem is. At least we've now got a nice simple example of a PyGTK program that creates a TreeView. :)
Anyway, it turns out that I was right when I guessed that the blue color of the selection turning to grey when the window loses focus on your computer is due to the behaviour of the window manager. I suppose there may be a way to block that in the application, by playing with Widget attributes, but I'm not sure how to do that. And besides, it's considered rude for programs to ignore the settings in the users' window theme.
So the most appropriate solution to your problem is to make the appropriate change in your window manager's appearance settings.
In KDE the relevant property is called "Inactive selection changes color", as described in Color Scheme Options:
Inactive selection changes color — If checked, the current selection in elements which do not have input focus will be drawn using a different color. This can assist visual identification of the element with input focus in some applications, especially those which simultaneously display several lists.
To change this, open up system settings (ALT+F2 → "systemsettings", or the [K] menu → system settings), then go to "Application appearance" and select "Colors". In the "Options" tab, uncheck the "Inactive selection changes color" setting, and click apply.
... ... ...
If you're not using KDE you'll have to figure out for yourself how to change it; hopefully, other window manager settings interfaces and documentation refer to this property with the same name or a similar name.
I can't find a way to hide QComboBox items. So far the only way to filter its items out is to delete the existing ones (with .clear() method). And then to rebuild the entire QComboBox again using its .addItem() method.
I would rather temporary hide the items. And when they are needed to unhide them back.
Is hide/unhide on QCombobox items could be accomplished?
In case someone still looking for an answer:
By default, QComboBox uses QListView to display the popup list and QListView has the setRowHidden() method:
qobject_cast<QListView *>(comboBox->view())->setRowHidden(0, true);
Edit: fix code according to #Tobias Leupold's comment.
Edit: Python version:
# hide row
view = comboBox.view()
view.setRowHidden(row, True)
# disable item
model = comboBox.model()
item = model.item(row)
item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
# enable item
view.setRowHidden(row, false)
item.setFlags(item.flags() | Qt.ItemIsEnabled)
To build on what #kef answered:
(excuse the C++ on the python question)
By default the QComboBox will use a QListView for the view, thus you can do the following:
QListView* view = qobject_cast<QListView *>(combo->view());
Q_ASSERT(view != nullptr);
view->setRowHidden(row, true);
The one drawback with the above is, that even though the item will be hidden from the popup, the user can still select it using the mouse wheel. To overcome this add the following for the hidden row:
QStandardItemModel* model = qobject_cast<QStandardItemModel*>(combo->model());
Q_ASSERT(model != nullptr);
QStandardItem* item = model->item(row);
item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
With the above the row will be hidden and the user will not be able to scroll to it with the mouse wheel.
To unhide it, just do the reverse:
view->setRowHidden(row, false);
item->setFlags(item->flags() | Qt::ItemIsEnabled);
You can use the removeItem() method to remove an item from the QComboBox.
void QComboBox::removeItem ( int index )
Removes the item at the given index from the combobox. This will update the current index if the index is removed.
This function does nothing if index is out of range.
If you don't know the index, use the findText() method.
There are no hide/unhide methods for QComboBox items.
Althought there is no direct way to hide the item of the QComboBox, but you can use QComboBox::setItemData and set the size to (0,0) to hide the item of QComboBox:
comboBox->setItemData(row, QSize(0,0), Qt::SizeHintRole);
Use the setVisible() to alter the visibility of your object:
.setVisible(False) # Not Visible
.setVisible(True) # Visible
To show the item again:
comboBox->setItemData(row, QVariant(), Qt::SizeHintRole);
Note: changing the SizeHintRole doesn't work on OS X.
I came across this thread after getting frustrated with a lack of hide functionality that would keep the item indexing etc.
I got it to work based on #Kef and #CJCombrink answers. This is basically just a python translation.
I had a problem with qobject_cast.
Solved it by setting .setView(QListView()) to the QComboBox.
combo=QComboBox()
combo.setView(QListView())
hide:
combo.view().setRowHidden(rowindex,True)
tmp_item=combo.model().item(rowindex)
tmp_item.setFlags(tmp_item.flags() & ~Qt.ItemIsEnabled)
unhide:
combo.view().setRowHidden(rowindex,False)
tmp_item=combo.model().item(rowindex)
tmp_item.setFlags(tmp_item.flags() | Qt.ItemIsEnabled)
I decided to subclass the QComboBox and add the hide functionality. Bellow is an use example for testing.
You are welcome to use it. I make no assurances.
import sys
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
#subclassed QComboBox with added hide row functionality
class ComboBox_whide(QComboBox):
def __init__(self):
super().__init__()
self.setView(QListView())#default self.view() is a QAbstractItemView object which is missing setRowHidden, therefore a QListView needs to be set
def hide_row_set(self,row,value=True):
"""sets the row accesibility
value=True hides the row"""
self.view().setRowHidden(row,value)#hides the item from dropdown, however the item is stil accesible by moving down with arrow keys or mouse wheel. The following disables solves that
tmp_item=self.model().item(row)
if value:#hide -> disable
tmp_item.setFlags(tmp_item.flags() & ~Qt.ItemIsEnabled)
else:#enable
tmp_item.setFlags(tmp_item.flags() | Qt.ItemIsEnabled)
def hide_row_toggle(self,row):
"""toggles the row accesibility"""
if self.view().isRowHidden(row):#is hidden, therefore make available
self.hide_row_set(row,False)
else:#is not hidden, therefore hide
self.hide_row_set(row,True)
class Main(QMainWindow):
def __init__(self):
super().__init__()
cwidg=QWidget()
clayer=QVBoxLayout()
cwidg.setLayout(clayer)
self.setCentralWidget(cwidg)
#button for testing
self.btn=QPushButton('Button')
self.btn.setCheckable(True)
clayer.addWidget(self.btn)
#subclassed QComboBox
self.combo=ComboBox_whide()
for n in range(3):#add 3 items with tooltips
self.combo.addItem('item%i'%n)
self.combo.setItemData(n,'tip%i'%n,Qt.ToolTipRole)
clayer.addWidget(self.combo)
#button test function - choose either or for testing
self.btn.clicked.connect(self.btn_clicked)
#uncomment for add/remove example self.btn.clicked.connect(self.remove_add_item)
def btn_clicked(self):
self.combo.hide_row_toggle(1)
def remove_add_item(self):# here for naive comparison and to show why removing and adding is not ok
if self.combo.count()==3:
self.combo.removeItem(1)
else:
self.combo.addItem('new')#new "item1" withouth the ToolTip
if __name__ == '__main__':
app = QApplication.instance()
if app is None:#Pyside2 ipython notebook check
app = QApplication(sys.argv)
main = Main()
main.show()
app.exec_()
I'm using a QStackedWidget where on Screen 1, I have a QTreeWidget with a list of items and Screen 2 has a few comboboxes and checkboxes. Double clicking on an item in the tree widget takes me to Screen 2. What I want to do is develop a way to remember chosen settings.
So for eg. if I double click on'Item1' in the treewidget, choose some options in the check and combo boxes in screen 2 and return to screen 1 and choose 'Item2' wherein this time I choose a different set of combo items etc. On going back to the first screen again and double clicking on 'Item1', I should restore the options I had previously associated with it.
Hope this makes sense. I needed help on the best way to do this and some code examples would be great.
Really appreciate any help.
All tree-widget items have a setData method that you can use to store associated values, which in this case would just be a dict containing the settings.
To make saving and restoring the settings easier, it would be advisable to make sure all the checkboxes, comboboxes, etc have a common parent, and that they are all given a unique objectName. That way, it will make it easy to iterate over them:
def saveSettings(self):
settings = {}
for child in self.settingsParent.children():
name = child.objectName()
if not name:
continue
if isinstance(child, QtGui.QCheckBox):
settings[name] = child.isChecked()
elif isinstance(child, QtGui.QComboBox):
settings[name] = child.currentIndex()
...
return settings
def restoreSettings(self, settings):
for child in self.settingsParent.children():
name = child.objectName()
if name not in settings:
continue
if isinstance(child, QtGui.QCheckBox):
child.setChecked(settings[name])
elif isinstance(child, QtGui.QComboBox):
child.setCurrentIndex(settings[name])
...
To add the settings to the tree-widget item, you just need to do something like this:
settings = self.saveSettings()
item.setData(0, QtCore.Qt.UserRole, settings)
and to retrieve them, do this:
settings = item.data(0, QtCore.Qt.UserRole)
self.restoreSettings(settings)
But note that you may need to take an extra step here if you are using python2, because data will return a QVariant, rather than a dict. If that is the case, to get the dict, you will need to do this instead:
settings = item.data(0, Qt.QtCore.Qt.UserRole).toPyObject()
Alternatively, you can get rid of QVariant everywhere but putting this at the beginning of your program:
import sip
sip.setapi('QVariant', 2)
from PyQt4 import ... etc