I need to get the focus back to the first input after write and press the enter key in another input. For instance, after enter a value in myPrecio input and press enter i need to get the focus back to myCodigo input, how can i achieve this?
import npyscreen
class MyGrid(npyscreen.GridColTitles):
# You need to override custom_print_cell to manipulate how
# a cell is printed. In this example we change the color of the
# text depending on the string value of cell.
def custom_print_cell(self, actual_cell, cell_display_value):
if cell_display_value =='FAIL':
actual_cell.color = 'DANGER'
elif cell_display_value == 'PASS':
actual_cell.color = 'GOOD'
else:
actual_cell.color = 'DEFAULT'
class nuevoIngreso(npyscreen.FormBaseNew):
def afterEditing(self):
self.parentApp.setNextForm(none)
def create(self):
self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Departmento', values = ['M', 'C', 'L'])
self.myCodigo = self.add(npyscreen.TitleText, name='CODIGO: ')
self.myDescripcion = self.add(npyscreen.TitleText, name='DESCRIPCION: ')
self.myKit = self.add(npyscreen.TitleText, name='UN/KIT: ')
self.myPrecio = self.add(npyscreen.TitleText, name='$/UN')
self.myGrid = self.add(MyGrid,select_whole_line = True,editable = False)
# Adding values to the Grid, this code just randomly
# fills a 2 x 4 grid with random PASS/FAIL strings.
self.myGrid.values = []
for x in range(3):
row = []
for y in range(4):
if bool(random.getrandbits(1)):
row.append("PASS")
else:
row.append("FAIL")
self.myGrid.values.append(row)
class MyApplication(npyscreen.NPSAppManaged):
def onStart(self):
F=self.addForm('MAIN', nuevoIngreso, name='Nuevo Ingreso')
# A real application might define more forms here.......
if __name__ == '__main__':
TestApp = MyApplication().run()
UPDATE: after some test, i added to my code:
self.myPrecio.entry_widget.handlers.update({curses.ascii.CR: self.input_send})
At the end of def Create(self) and i added this function to attach bind to enter key on TitleText widget:
def input_send(self, _input):
#self.myCodigo.editing = False
#self.myDescripcion.editing = False
#self.myKit.editing = False
#self.myGrid.editing = False
#self.myPrecio.editing =
self.display()
self.editw=1
self.myPrecio.editing = False
self.editing = False
self.edit()
Now i can set focus on field myCodigo, but the cursor is also displayed on field myPrecio as follow:
Related
I'm using the code from https://jeanbilheux.pages.ornl.gov/post/right_click_menu_in_pyqt_table/ to show a menu when the user pressed right click on a cell in Table widget, on top of it I'm also getting the row/header if the user pressed left click.
This section is done and works well.
My question: how can I get the cell position (Header/Row) where the user pressed right click? (function: cell_right_click)
There are few articles about this issue and I tried most of them without any progress.
Who can help me?
This is a partial of my code:
...
My table definition:
self.tableWidget = QtWidgets.QTableWidget(self.frame)
self.tableWidget.cellClicked.connect(self.cell_was_clicked)
self.tableWidget.setGeometry(QtCore.QRect(10, 460, 1732, 465))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Change table header color
# stylesheet = "::section{Background-color:rgb(107,121,126);border-radius:14px;color: white;}"
stylesheet = "::section{Background-color:rgb(107,121,126);color: white;}"
self.tableWidget.horizontalHeader().setStyleSheet(stylesheet)
# How many coulmns
self.tableWidget.setColumnCount(23)
self.tableWidget.setRowCount(0)
#Function to handle cell click
self.tableWidget.cellClicked.connect(self.cell_was_clicked)
...
def cell_was_clicked(self, row, column):
item = self.tableWidget.selectedItems()
value = item[0].text()
columnNmame = self.tableWidget.horizontalHeaderItem(column).text()
print(columnNmame)
def cell_right_click(self, position):
table_hnd = tableHandler(parent=self)
table_hnd.right_click()
class tableHandler:
def __init__(self, parent=None):
self.parent = parent
def right_click(self):
#bar = self.parent.menuBar()
top_menu = QMenu(MainWindow.menuBar())
menu = top_menu.addMenu("Menu")
config = menu.addMenu("Configuration ...")
_load = config.addAction("&Load ...")
_save = config.addAction("&Save ...")
config.addSeparator()
config1 = config.addAction("Config1")
config2 = config.addAction("Config2")
config3 = config.addAction("Config3")
action = menu.exec_(QtGui.QCursor.pos())
if action == _load:
# do this
pass
elif action == _save:
# do this
pass
elif action == config1:
# do this
pass
elif action == config2:
# do this
pass
elif action == config3:
# do this
pass
trying to make this work
import maya.cmds as mc
def firstFace():
FaceToSel = 'first' def allFace():
FaceToSel = 'all'
def execute():
if FaceToSel == 'first':
print Yes
elif FaceToSel == 'all':
print No
def ui():
if mc.window('face_Select', exists = True):
mc.deleteUI('face_Select')
FaceWin = mc.window('face_Select', mxb = False)
mc.columnLayout( adjustableColumn = True )
mc.intFieldGrp( 'numberOfFaces', label = 'Number Of Facess', value1 = 10 )
ButtonOne = mc.radioButtonGrp( label='Type', labelArray3=['TopFaces', 'Allfaces'], numberOfRadioButtons = 2, onCommand1 = 'firstFace()', onCommand2 = 'lastFace()')
mc.button( label = 'Select faces', command = 'execute()', align = 'center', aop = True)
mc.showWindow('face_Select')
ui()
First ask a question.
Then provide a code with indentation, put Yes and No with comma, check that your functions has a def that exists, command flags that has correct datas and it will be more easy to make you an answer.....
So here is a working code, if you want more explanation, check question about ui I've answered
How to use a slider value in calculations?
import maya.cmds as mc
from functools import partial
def execute(FaceToSel, *args):
option = mc.radioButtonGrp(FaceToSel, q=True, select=True)
if option == 1:
print True
elif option == 2:
print False
def ui():
if mc.window('face_Select', exists = True):
mc.deleteUI('face_Select')
FaceWin = mc.window('face_Select', mxb = False)
mc.columnLayout( adjustableColumn = True )
mc.intFieldGrp( 'numberOfFaces', label = 'Number Of Facess', value1 = 10 )
ButtonOne = mc.radioButtonGrp( label='Type', labelArray2=['TopFaces', 'Allfaces'], numberOfRadioButtons = 2, select=1)
mc.button( label = 'Select faces', command = partial(execute, ButtonOne), align = 'center', aop = True)
mc.showWindow('face_Select')
ui()
I am trying to write a script that, on button press with a joint selected, will copy the transform values from the selected joint(s) and then create a controller selected from an option menu. My problem is getting the code to read the option menu. I've tried several variations and all say there is no option menu with the selected name.
Code follows....
import maya.cmds as maya
def testWin():
winName = maya.window(title="test", rtf = True, mxb = False)
maya.columnLayout()
maya.button(label = "run test", c = "test()")
shapeMenu = maya.optionMenu( label='Shape Menu', changeCommand="test()" )
maya.menuItem( label='Circle' )
maya.menuItem( label='Square' )
maya.menuItem( label='Triangle' )
maya.showWindow(winName)
testWin()
def test():
sel = maya.ls(type = "joint", sl=True)
if not sel:
print "select at least 1 JOINT"
else:
new_pos = maya.xform(q=True, t=True, ws=True)
new_rot = maya.xform(q=True, rotation=True, ws=True)
shape = maya.optionMenu("Shape Menu", q = True, value = True)
if shape == "Circle":
new_control = maya.circle(center = new_pos)
elif shape == "Square":
new_control = maya.nurbsSquare(center = new_pos)
elif shape == "Triangle":
new_control = maya.circle(center = new_pos, degree = 1, sections = 3)
You can't be sure that maya will give you the name you asked for when creating a GUI object -- an in this case it will never work because the name that comes back will not have the space.
You should capture the name of the option menu by returning the value of shapeMenu from your testWin() function then use that in your test() function
I am trying to code a menu routine for an alarm-clock in python, which displays the relevant information on a 7-segment display according to some inputs via pushbuttons.
I managed to create a loop which displays the current time, and whe the button "debMenu" is clicked 3 menu options are displayed. This works well only for the first time untill the 3rd. menu option is reached. When I push the button again the routine does not work - so the function "main_menu" is not called again.
What I am doing wrong...? Thanks !!
stop_loop = [False]
def main_menu(stop_loop, n=[0]):
stop_loop[0] = True
debSelect = DebouncedSwitch(butSelect, cbButSelect, "butSelect")
menuList = ['HO ', 'AL ', 'UP ']
if n[0] < 3:
display.scroll(menuList[n[0]], 200) #display menu on 7-seg display
display.show(menuList[n[0]])
n[0] += 1
elif n[0] == 3:
n=[0]
stop_loop[0] = False
main()
def main():
stop_loop[0] = False
debMenu = DebouncedSwitch(butMenu, main_menu, stop_loop)
while not stop_loop[0]: # display current time on 7-seg display
curTime = rtc.datetime()
display.numbers(curTime.hour, curTime.minute, False)
time.sleep_ms(500)
display.numbers(curTime.hour, curTime.minute)
time.sleep_ms(500)
main()
I guess the default value mutable variable is the one killing you. Check here: http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments.
I don't even understand why you need a list variable in this case, why not just n=0 without having to use a list?.
maybe make a new global variable or class to encapsulate both state-related variables (stop_loop and n). Like:
loop = dict(stop=False, n=0)
now you pass this instead of stop_loop to main_menu.
Or use a class that encapsulates a circular array for menu like:
class LoopMenu:
""" circular array menu list with pause/continue/next"""
def __init__(self, menu):
self.menu = menu
self.stop = False
self.n = 0
def next(self):
menu = self.menu[self.n]
self.n += 1
if self.n > len(self.menu):
self.n = 0
return menu
def pause(self):
self.stop = True
def play(self):
self.stop = False
then you main_menu method could be:
my_menu_loop = LoopMenu(['HO ', 'AL ', 'UP '])
def main_menu(menu_loop):
menu_loop.pause()
debSelect = DebouncedSwitch(butSelect, cbButSelect, "butSelect")
menu = menu_loop.next()
display.scroll(menu, 200) #display menu on 7-seg display
display.show(menu)
main()
def main():
my_menu_loop.play()
debMenu = DebouncedSwitch(butMenu, main_menu, my_menu_loop)
while not loop_menu.stop: # display current time on 7-seg display
curTime = rtc.datetime()
display.numbers(curTime.hour, curTime.minute, False)
time.sleep_ms(500)
display.numbers(curTime.hour, curTime.minute)
time.sleep_ms(500)
main()
I have a method that checks that a pyqt spinbox value has been entered, the required values are 1 through 18 inclusive so I initiate the spinbox with the value 0 so that I can easily tell its not been changed to the correct number. I thought that if the check finds its still 0 the user forget to set it and a warning pops up to let them know..
The problem I have is that the window pops up, user presses OK, the pop up closes but immediately opens again before the user has had time to set the correct value ... how can I have the pop up close and allow the user time to change the spinbox to the correct value before it checks for 0 and pops up again (if still not correct)
the signal that triggers group_check was originally triggering the pickFile method until I realised that the code executed whether Group No was set in the spinbox or not, I had tried to build the check into the pickFile method but then though it might be best to separate it out.
import sys
import time
from PyQt4 import QtGui, uic
import xlrd
import csv
import os
import re
qtCreatorFile = "UI1.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
group = ''
group_1 = ''
Var_1 = ''
Var_2 = ''
Var_3 = ''
error_string = ''
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.file_picker_button.clicked.connect(self.group_check)
self.radioButton_1.clicked.connect(self.onRadioButton1)
self.radioButton_2.clicked.connect(self.onRadioButton2)
self.radioButton_3.clicked.connect(self.onRadioButton3)
self.spinBox.valueChanged.connect(self.valuechange)
def group_check(self):
while True:
if self.spinBox.value() == 0:
error_string ='You must select your\nGroup No first ! ok ? '
self.error_msg(error_string)
else:
self.pickFile()
def pickFile(self):
while True:
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '.')
if 'Monday' in filename:
break
elif 'Monday' not in filename or filename == '':
error_string ='Wrong file ? \nWant to try again ?'
self.error_msg1(error_string)
else:
self.filename = filename
x = first_file()
x.csv_from_excel(filename)
def onRadioButton1(self, group):
MyApp.Var_1 = 'PGDE SECONDARY ONLY'
MyApp.Var_2 = 'MA4 ONLY'
MyApp.Var_3 = 'PGDE'
def onRadioButton2(self, group):
MyApp.Var_1 = 'PGDE PRIMARY ONLY'
MyApp.Var_2 = 'MA4 ONLY'
MyApp.Var_3 = 'PGDE'
def onRadioButton3(self, group):
MyApp.Var_1 = 'PGDE PRIMARY ONLY'
MyApp.Var_2 = 'PGDE SECONDARY ONLY'
MyApp.Var_3 = 'MA4'
def valuechange(self, value):
MyApp.group_1 = ('Group '+ str(self.spinBox.value()))
if self.spinBox.value() >= 10:
MyApp.group = "1-9 ONLY"
if self.spinBox.value() >= 1 and self.spinBox.value() <= 9:
MyApp.group = "10-18 ONLY"
def error_msg(self, error_string):
choice = QtGui.QMessageBox.question(self, 'Error!', error_string)
Instead of using while True just display the error message and return from the function. Make them click the button again after they fix the error
def group_check(self):
if self.spinBox.value() == 0:
error_string ='You must select your\nGroup No first ! ok ? '
self.error_msg(error_string)
return
self.pickFile()