Pop up warning box - python

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()

Related

how to get focus in TitleText input from npyscreen?

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:

TypeError: bott() takes 1 positional argument but 2 were given even with self

I have self in all functions, but I still get the error in the title. I don't know what to try, any help?
Here is the code:
class layy(App):
global t
t = TextInput(hint_text='insert text')
global c
global s
s = TextInput(hint_text='insert time till begin')
c = TextInput(hint_text='insert amount')
def bott(self):
am = c.text
if (am == ""):
am = '0'
l = int(am)
pm = c.text
if (pm == ""):
pm = '0'
o = int(pm)
base = 0
time.sleep(o)
while (base < l):
pyautogui.typewrite(t)
pyautogui.press('enter')
base = base + 1
def build(self):
b = Button(text = 'Start Spam')
b.bind(on_press = self.bott)
layout = BoxLayout(orientation='vertical')
sublay1 = BoxLayout(orientation='horizontal')
sublay2 = BoxLayout(orientation='horizontal')
sublay3 = BoxLayout(orientation='horizontal')
layout.add_widget(sublay1)
sublay1.add_widget(t)
layout.add_widget(sublay2)
sublay2.add_widget(s)
sublay2.add_widget(c)
layout.add_widget(sublay3)
sublay3.add_widget(b)
return layout
if __name__ == '__main__':
layy().run()
If any more information is needed, this is supposed to repeat sending the desired text as many times as I need. If anyone knows what to do, please tell me.
Kivy event handlers can take any number of parameters. I haven't found a good source for what parameters are given for each callback type, but the Button has an example that uses on_press and it receives the button instance being pressed. That's the second mystery parameter the error references. Just add it to your method
def bott(self, instance):
do the things...

PYQT: QTableView. Filter Between Dates

I've created a GUI that allows users to modify, filter update and delete from a sqlite database. Everything is working great except the date range filter. When I run the code, I don't get an error, I only get a blank filtered screen with no data. Does anyone see what's wrong with my code? [Section 1a, subgroup{v} is what I am seeking help on]. Thanks!
from PyQt4 import QtCore, QtGui, QtSql
import sys
import sqlite3
import time
import Search #imported ui.py MainWindow file
import os
try:
from PyQt4.QtCore import QString
except ImportError:
QString = str
class TableEditor(QtGui.QMainWindow, Search.Search_MainWindow):
def __init__(self, tableName, parent=None):
super(self.__class__, self).__init__()
self.setupUi(self)
self.model = QtSql.QSqlTableModel(self)
self.model.setTable('CAUTI')
self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.model.select()
self.model.setHeaderData(0, QtCore.Qt.Horizontal, "MRN")
self.model.setHeaderData(1, QtCore.Qt.Horizontal, "Last Name")
self.model.setHeaderData(2, QtCore.Qt.Horizontal, "First Name")
self.model.setHeaderData(3, QtCore.Qt.Horizontal, "Date of Event")
self.model.setHeaderData(4, QtCore.Qt.Horizontal, "Facility")
self.model.setHeaderData(5, QtCore.Qt.Horizontal, "Unit")
self.model.setHeaderData(6, QtCore.Qt.Horizontal, "User")
self.tableView.setModel(self.model)
self.setWindowTitle("HAI Table")
self.tableView.setColumnWidth(0,100)
self.tableView.setColumnWidth(1,100)
self.tableView.setColumnWidth(2,100)
self.tableView.setColumnWidth(3,100)
self.tableView.setColumnWidth(4,100)
self.tableView.setColumnWidth(5,100)
self.tableView.setColumnWidth(6,83)
self.submitButton.clicked.connect(self.submit)
self.revertButton.clicked.connect(self.model.revertAll)
self.quitButton.clicked.connect(self.close)
current = QtCore.QDateTime.currentDateTime()
self.startDate.setDate(current.date())
self.endDate.setDate(current.date())
self.startDate.setDisplayFormat("M/dd/yyyy")
self.endDate.setDisplayFormat("M/dd/yyyy")
# Section 1: Signals
# {i} Search Fields Button Emitted:
# [1]
self.search_MRN_Button.clicked.connect(self.search_MRN_FilterRecord)
# [2]
self.search_Lname_Button.clicked.connect(self.search_Lname_FilterRecord)
# [3]
self.search_Unit_Button.clicked.connect(self.search_Unit_FilterRecord)
# {ii} Search Clear Buttons Emitted:
# [1]
self.search_MRN_CancelButton.clicked.connect(self.search_MRN_CancelButton_Clicked)
# [2]
self.search_Lname_CancelButton.clicked.connect(self.search_Lname_CancelButton_Clicked)
# [3]
self.search_Unit_CancelButton.clicked.connect(self.search_Unit_CancelButton_Clicked)
# {iii} Search Fields Button Emitted:
# [1]
self.search_MRN.selectionChanged.connect(self.search_MRN_Edit)
# [2]
self.search_Lname.selectionChanged.connect(self.search_Lname_Edit)
# [3]
self.search_Unit.selectionChanged.connect(self.search_Unit_Edit)
# {iv} Search Fields Button Emitted:
# [1]
self.search_MRN.returnPressed.connect(self.search_MRN_Enter)
# [2]
self.search_Lname.returnPressed.connect(self.search_Lname_Enter)
# [3]
self.search_Unit.returnPressed.connect(self.search_Unit_Enter)
#{v} Search Between 2 Dates
self.btnSubmit.clicked.connect(self.FilterBetweenDates)
# Section 1a: Slots from Section 1.
#{i} Search Field Button Slots:
#[1]
def search_MRN_FilterRecord(self):
text = self.search_MRN.text()
if len(text) == 0:
self.model.setFilter("")
else:
self.model.setFilter("MRN like'" +self.search_MRN.text()+ "%%'")
#self.model.setFilter("MRN = '%s'" % text)
#[2]
def search_Lname_FilterRecord(self):
text = self.search_Lname.text()
if len(text) == 0:
self.model.setFilter("")
else:
self.model.setFilter("Surname like'" +self.search_Lname.text()+ "%'")
#self.model.setFilter("Surname = '%s'" % text) #This line of code will only pull exact matches.
#[3]
def search_Unit_FilterRecord(self):
text = self.search_Unit.text()
if len(text) == 0:
self.model.setFilter("")
else:
self.model.setFilter("Unit like'" +self.search_Unit.text()+ "%'")
#self.model.setFilter("Unit = '%s'" % text) #This line of code will only pull exact matches.
#{ii} Search Field Cancel Button Slots:
#[1]
def search_MRN_CancelButton_Clicked(self):
self.model.setFilter("")
self.search_MRN.setText("MRN Search")
#[2]
def search_Lname_CancelButton_Clicked(self):
self.model.setFilter("")
self.search_Lname.setText("Last Name Search")
#[3]
def search_Unit_CancelButton_Clicked(self):
self.model.setFilter("")
self.search_Unit.setText("Unit Search")
#{iii} Search Text Edited Slots:
#[1]
def search_MRN_Edit(self):
self.search_MRN.setText("")
#[2]
def search_Lname_Edit(self):
self.search_Lname.setText("")
#[3]
def search_Unit_Edit(self):
self.search_Unit.setText("")
#{iv} Search Text Return Pressed (Enter) Slots:
#[1]
def search_MRN_Enter(self):
self.search_MRN_FilterRecord()
#[2]
def search_Lname_Enter(self):
self.search_Lname_FilterRecord()
#[3]
def search_Unit_Enter(self):
self.search_Unit_FilterRecord()
#{v} Filter Between Dates, Slot:
def FilterBetweenDates(self):
start = str(self.startDate.text())
finish = str(self.endDate.text())
self.model.setFilter("EventDate BETWEEN'" + start and finish)
def submit(self):
self.model.database().transaction()
if self.model.submitAll():
self.model.database().commit()
else:
self.model.database().rollback()
QtGui.QMessageBox.warning(self, "HAI Table",
"The database reported an error: %s" % self.model.lastError().text())
def main():
app = QtGui.QApplication(sys.argv)
#app.setStyle( "Plastique" )
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('HAI.db')
editor = TableEditor('CAUTI')
editor.show()
app.exec_()
if __name__ == '__main__':
The and in your filter text should part of the filter string. Now you are taking the logical-and of two strings (which will be the last string unless the first is empty) and append that to the filter string.
So change
self.model.setFilter("EventDate BETWEEN'" + start and finish)
to
filter = "EventDate BETWEEN '{}' AND '{}'".format(start, finish)
print(filter) # for debugging
self.model.setFilter(filter)
During debugging, it's probably a good idea to print the filter string and try it out in an SQL query (directly in the sqlite3 tool) so that you can see it works.

QCheckBox state change PyQt4

I'm trying to implement a system in PyQt4 where unchecking a checkbox would call function disable_mod and checking it would call enable_mod. But even though state is changing the checkboxes call the initial function they started with. For this case if an already checked box was clicked it'd always keep calling the disable_mod function! I don't understand why is this happening? Can you guys help me out here a little bit? Here's my code:
from PyQt4 import QtCore, QtGui
from os import walk
from os.path import join
import sys
def list_files_regex(dir):
l = []
for (root, dirnames, filenames) in walk(dir):
for d in dirnames:
list_files_regex(join(root, d))
l.extend(filenames)
return l
directory = "J:/test_pack"
directory = join(directory, "/mods")
count = 0
for y in list_files_regex(directory):
print y
count += 1
print count
class ModEdit(QtGui.QMainWindow):
def __init__(self, title, icon, x, y, w, h):
super(ModEdit, self).__init__()
self.setWindowTitle(title)
self.setWindowIcon(QtGui.QIcon(icon))
self.setGeometry(x, y, w, h)
self.choices = []
self.init()
def init(self):
scroll_widget = QtGui.QScrollArea()
sub_widget = QtGui.QWidget()
v_layout = QtGui.QVBoxLayout()
for y in list_files_regex(directory):
tmp = QtGui.QCheckBox(y, self)
tmp.resize(tmp.sizeHint())
if tmp.text()[len(tmp.text()) - 8: len(tmp.text())] != 'disabled':
tmp.setChecked(True)
# if tmp.isChecked() == 0:
# tmp.stateChanged.connect(self.enable_mod)
# if tmp.isChecked():
# tmp.stateChanged.connect(self.disable_mod)
# v_layout.addWidget(tmp)
self.choices.append(tmp)
print self.choices
for choice in self.choices:
v_layout.addWidget(choice)
if choice.isChecked():
choice.stateChanged.connect(self.disable_mod)
else:
choice.stateChanged.connect(self.enable_mod)
sub_widget.setLayout(v_layout)
scroll_widget.setWidget(sub_widget)
self.setCentralWidget(scroll_widget)
self.show()
def enable_mod(self):
print "ENABLE_TEST"
print self.choices[1].isChecked()
def disable_mod(self):
print "DISABLE_TEST"
print self.choices[1].isChecked()
def test(self):
print 'test'
for ch in self.choices:
if ch.isChecked():
ch.stateChanged.connect(self.disable_mod)
else:
ch.stateChanged.connect(self.enable_mod)
class Rename(QtCore.QObject):
enable = QtCore.pyqtSignal
disable = QtCore.pyqtSignal
app = QtGui.QApplication(sys.argv)
ex = ModEdit("Minecraft ModEdit", "ModEdit.png", 64, 64, 640, 480)
sys.exit(app.exec_())
The problem is that you're only connecting the checkbox stateChanged signal once during initialization. After the state of the checkbox changes, you're not disconnecting the signal and reconnecting it to the correct slot.
You'll need to connect the stateChanged signal to an intermediary slot that will decide which function to call based on the checkbox state. Since you're using the same slot for multiple checkboxes, it's probably best to also pass the checkbox to the slot as well.
from functools import partial
def init(self):
...
for tmp in list_of_checkboxes:
enable_slot = partial(self.enable_mod, tmp)
disable_slot = partial(self.disable_mod, tmp)
tmp.stateChanged.connect(lambda x: enable_slot() if x else disable_slot())
def enable_mod(self, checkbox):
print "ENABLE_TEST"
print checkbox.isChecked()
def disable_mod(self, checkbox):
print "DISABLE_TEST"
print checkbox.isChecked()
Alternatively, since we are now passing the checkbox to the slots, you could just use a single slot and check the checkbox state inside the slot
def init(self):
...
for tmp in list_of_checkboxes:
slot = partial(self.enable_disable_mod, tmp)
tmp.stateChanged.connect(lambda x: slot())
def enable_disable_mod(self, checkbox):
if checkbox.isChecked():
...
else:
...

Getting selected text (python-gtk)

I want to get selected text automatically in python, using gtk module.
There is a code to get selected text from anywhere:
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class GetSelectionExample:
# Signal handler invoked when user clicks on the
# "Get String Target" button
def get_stringtarget(self, widget):
# And request the "STRING" target for the primary selection
ret = widget.selection_convert("PRIMARY", "STRING")
return
# Signal handler called when the selections owner returns the data
def selection_received(self, widget, selection_data, data):
# Make sure we got the data in the expected form
if str(selection_data.type) == "STRING":
# Print out the string we received
print "STRING TARGET: %s" % selection_data.get_text()
elif str(selection_data.type) == "ATOM":
# Print out the target list we received
targets = selection_data.get_targets()
for target in targets:
name = str(target)
if name != None:
print "%s" % name
else:
print "(bad target)"
else:
print "Selection was not returned as \"STRING\" or \"ATOM\"!"
return False
def __init__(self):
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Get Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
# Create a button the user can click to get the string target
button = gtk.Button("Get String Target")
eventbox = gtk.EventBox()
eventbox.add(button)
button.connect_object("clicked", self.get_stringtarget, eventbox)
eventbox.connect("selection_received", self.selection_received)
vbox.pack_start(eventbox)
eventbox.show()
button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
GetSelectionExample()
main()
But i don't want to this exactly.
i dont want to click a button. I want to see the selected text only, not after a button clicking. When i start the program ; it must show me the selected text automatically (without clicking any button!).
I want to this exactly :
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class MyApp (object):
def __init__(self):
self.window=gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("delete_event", gtk.main_quit )
self.entry = gtk.Entry()
try:
self.s_text=gtk.SelectionData.get_text
# i expect that : the selected text (from anywhere)
# but it returns me :
#<method 'get_text' of 'gtk.SelectionData' objects>
except:
self.s_text="it must be selected text"
self.entry.set_text("Selected Text is : %s" % self.s_text )
self.window.add(self.entry)
self.window.show_all()
def main(self):
gtk.main()
app=MyApp()
app.main()
This program must show me the selected text in the entry box automatically.
Only this. But i can't do!
i expect " gtk.SelectionData.get_text " will show me the selected text but it returns "<method 'get_text' of 'gtk.SelectionData' objects>" .
And also i tried self.s_text=gtk.SelectionData.get_text()
But it returns me :
self.s_text=gtk.SelectionData.get_text()
TypeError: descriptor 'get_text' of 'gtk.SelectionData' object needs an argument
How can i do this? And also i am a beginner python programmer; if u can write the code ; it will be very good for me :)
thanks a lot !!
self.s_text=gtk.SelectionData.get_text
Method get_text is not called yet! You are assigning self.s_text to the method(function) object itself. Which is converted to string in "Selected Text is : %s" % self.s_text
You should changed it to:
self.s_text=gtk.SelectionData.get_text()
EDIT: But since you need a SelectionData object to pass to this method, the whole idea is wrong. I combined you two codes as something working:
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class MyApp (object):
def __init__(self):
self.window=gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("delete_event", gtk.main_quit )
self.entry = gtk.Entry()
self.window.selection_convert("PRIMARY", "STRING")
self.window.connect("selection_received", self.selection_received)
self.window.add(self.entry)
self.window.show_all()
# Signal handler called when the selections owner returns the data
def selection_received(self, widget, selection_data, data):
print 'selection_data.type=%r'%selection_data.type
# Make sure we got the data in the expected form
if str(selection_data.type) == "STRING":
self.entry.set_text("Selected Text is : %s" % selection_data.get_text())
elif str(selection_data.type) == "ATOM":
# Print out the target list we received
targets = selection_data.get_targets()
for target in targets:
name = str(target)
if name != None:
self.entry.set_text("%s" % name)
else:
self.entry.set_text("(bad target)")
else:
self.entry.set_text("Selection was not returned as \"STRING\" or \"ATOM\"!")
return False
def main(self):
gtk.main()
app=MyApp()
app.main()

Categories