Execute function of another class in kivy - python-3.x

Going straight to the point: I would like to click on the MDFilRoundFlatButton button in the ContentButton class and execute the close_order function in the TelaClose class
Can anyone help me on this one?
I'm still a little confused about executing functions from other classes, especially with kivy.
I've come a long way in this matter, I could use root.get_screen(... but I get an error saying that my class doesn't have the object to be executed.
from kivy.utils import get_color_from_hex
from kivymd.uix.button import MDRoundFlatIconButton
from kivymd.color_definitions import colors
from kivymd.uix.button import MDFillRoundFlatButton, MDRaisedButton
from kivymd.font_definitions import theme_font_styles
from kivymd.uix.label import MDLabel
import json
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd import images_path
from kivymd.uix.expansionpanel import MDExpansionPanel, MDExpansionPanelOneLine
from kivy.uix.screenmanager import Screen
from kivymd.uix.list import (
ImageLeftWidget,
ThreeLineIconListItem,
OneLineListItem,
)
# Imports para trabalhar com Firebase
from config import config
import pyrebase
import requests
from datetime import date
from datetime import datetime
today = date.today()
today_now = datetime.now()
Builder.load_string("""
<Content>
adaptive_height: True
orientation: 'vertical'
# TwoLineIconListItem:
# text: "(050)-123-45-67"
# secondary_text: "Mobile"
#
# IconLeftWidget:
# icon: 'phone'
<ContentButton>
orientation: 'vertical'
adaptive_height: True
MDFillRoundFlatButton:
size_hint: .9, None
pos_hint: {'center_x': .5, 'center_y': .5}
text: "Fechar Pedido"
on_release: root.fechar_pedido()
<TelaFechamento>:
name: 'tela_fechamento'
ScrollView:
pos_hint: {"top": .89}
MDGridLayout:
id: box
cols: 1
adaptive_height: True
""")
class InvoicePanel(MDExpansionPanel):
pass
class Content(MDBoxLayout):
'''Custom content.'''
class ContentButton(MDBoxLayout):
'''Custom content.'''
# Classe criada para permitir alinhamento
class OneLineListItemAligned(OneLineListItem):
def __init__(self, halign, **kwargs):
super(OneLineListItemAligned, self).__init__(**kwargs)
self.ids._lbl_primary.halign = halign
class TelaFechamento(Screen):
def fechar_pedido(self):
# Inicializando o banco de dados.
firebase = pyrebase.initialize_app(config)
db = firebase.database()
app = MDApp.get_running_app()
user_profiles = db.child('UserProfile').child(str(app.logged_user)).get(
token=app.USER_MASTER)
idpedido = {}
# Preenchendo os dados das listas
for produto in user_profiles.each():
if 'Cart' in produto.key():
items = produto.val().get('Cart')
for k, v in items['Opened'].items():
idpedido[k] = v
chave = datetime.now().strftime("%Y%m%d%H%M%S%f")
#print(json.dumps(id_pedido, indent=4))
# ********************************************************************************************************************************
# Criar pedidos importados no WShop
db.child('UserProfile').child(str(app.logged_user)).child(produto.key()).child('Confirmed').child(
chave).set(idpedido, token=app.USER_MASTER)
# Aqui abaixo devo criar o código para excluir de Cart
# Code here, Code here, Code here, .....
def pedidos_abertos(self):
# Inicializando o banco de dados.
firebase = pyrebase.initialize_app(config)
db = firebase.database()
app = MDApp.get_running_app()
json_data = db.child('UserProfile').child(str(app.logged_user)).get(
token=app.USER_MASTER)
for produtos in json_data.each():
#print(json.dumps(produtos.key(), indent=4))
if produtos.key() == 'Cart':
cart = produtos
try:
openeds = cart.val()['Opened']
#print(json.dumps(openeds, indent=4), '...............')
# adicionar fatura como item principal
cw = Content() # preencha o conteúdo à medida que os dados são analisados
ep = InvoicePanel(icon="./images/pedidos/shopping-cart.png", panel_cls=MDExpansionPanelOneLine(text=f'Produtos no carrinho:'),
content=cw)
self.ids.box.add_widget(ep)
# -----------------------------------------------------
# Cria o Widget Especificamente para fechar o pedido.
# close_items = MDRaisedButton(
# text="[color=ffffff]FATURAR ESTES ITENS[/color]", size_hint=(.9, .9))
# cw.add_widget(close_items)
close_items = OneLineListItemAligned(
text='Fechar este pedido agora?',
md_bg_color=app.theme_cls.primary_dark,
halign="center", font_style="H6", on_press=self.fechar_pedido)
# close_items.bind(on_release=print("----------Click!"))
cw.add_widget(close_items)
# -----------------------------------------------------
cw.add_widget(ContentButton())
for key_item, value_item in openeds.items():
#print(json.dumps(key_item, indent=4), '************* key_item')
# Cria a imagem que será usada no TwoLineIconListItem.
image = ImageLeftWidget(
source=value_item['url']
)
# Cria o Widget conforme sua escolha.
items = ThreeLineIconListItem(text=value_item['product_code'],
secondary_text=value_item['product_description'],
tertiary_text='{} x R${} = R${}'.format(value_item['quantidade'], value_item['price'], value_item['total_item']), md_bg_color=get_color_from_hex('#FFFDE7'))
# Adiciona a imagem ao Widget acima.
items.add_widget(image)
cw.add_widget(items)
except:
print('Ainda não possui pedidos!')
def pedidos_faturados(self):
# Inicializando o banco de dados.
firebase = pyrebase.initialize_app(config)
db = firebase.database()
app = MDApp.get_running_app()
json_data = db.child('UserProfile').child(str(app.logged_user)).get(
token=app.USER_MASTER)
for produtos in json_data.each():
#print(json.dumps(produtos.key(), indent=4))
if produtos.key() == 'Cart':
cart = produtos
try:
invoices = cart.val()['Invoice']
for key_invoice, value_invoice in invoices.items():
#print(json.dumps(value_invoice, indent=4))
# adicionar fatura como item principal
cw = Content() # preencha o conteúdo à medida que os dados são analisados
ep = InvoicePanel(icon='./images/pedidos/invoice.png', panel_cls=MDExpansionPanelOneLine(text=f'Confirmado: {key_invoice}'),
content=cw)
self.ids.box.add_widget(ep)
for key_item, value_item in value_invoice.items():
#print(json.dumps(key_item, indent=4))
# Cria a imagem que será usada no TwoLineIconListItem.
image = ImageLeftWidget(
source=value_item['url']
)
# Cria o Widget conforme sua escolha.
items = ThreeLineIconListItem(text=value_item['product_code'],
secondary_text=value_item['product_description'],
tertiary_text='{} x R${} = R${}'.format(value_item['quantidade'], value_item['price'], value_item['total_item']))
# Adiciona a imagem ao Widget acima.
items.add_widget(image)
cw.add_widget(items)
except:
print('Ainda não possui pedidos!')
def on_enter(self):
self.pedidos_abertos()
self.pedidos_faturados()
def on_kv_post(self, base_widget):
app = MDApp.get_running_app()

I think I found the best approach to this.
We must start from the app and go navigating until we reach the window where the class is and after finding execute the function.
<ContentButton>
orientation: 'vertical'
adaptive_height: True
MDFillRoundFlatButton:
size_hint: .9, None
pos_hint: {'center_x': .5, 'center_y': .5}
text: "Fechar Pedido"
on_release: print(app.root.get_screen('main_screen').ids.screen_manager.get_screen('tela_fechamento').fechar_pedido())

Related

Why doesn't plotly show the graph, when I execute the same statements inside a class?

I am learning classes. The script below, shows the graph correctly using plotly express, but if I integrate it as a method in a class, it doesn't.
I show the classes below. With the first one, we import quotes from Yahoo! With the second, we try to represent a graph of the imported normalized prices.
import pandas as pd
import pandas_datareader as pdr
import datetime as dt
from datetime import date
from plotly.offline import iplot
import plotly.express as px
class ImportadorCotizaciones:
def __init__(self):
self.cotizaciones = None
self.start = "2000-1-4"
self.end = date.today()
self.cotizaciones = None
def Importar_cotizaciones(self):
dicc_tickers = {"IBE.MC":"Iberdrola", "TEF.MC":"Telefonica", "^IBEX":"Ibex35" }
dfs = []
nombres = []
for (k,v) in dicc_tickers.items():
self.cotizaciones_de_ticker = pdr.DataReader(k, 'yahoo', self.start, self.end)
self.cotizaciones_de_ticker = self.cotizaciones_de_ticker[["Close"]]
self.cotizaciones_de_ticker = self.cotizaciones_de_ticker.rename(columns={"Close": v})
dfs.append(self.cotizaciones_de_ticker)
dfs = iter(dfs)
self.cotizaciones = next(dfs)
for df_ in dfs:
self.cotizaciones = self.cotizaciones.merge(df_, on='Date')
class Indicadores:
def __init__(self, importador):
self.importador = importador
def dibujar_grafico(self):
self.aux_val_ind = importador.cotizaciones[["Iberdrola", "Ibex35"]].pct_change().dropna()
df = self.aux_val_ind.copy(deep=True)
df['Media'] = df.mean(axis = 1)
# Usando plotly.express
px.line((df + 1).cumprod() ,y=df.columns ,title=f"\nValor de 1€ invertido desde el { importador.start} hasta el {importador.end} ")
importador = ImportadorCotizaciones()
importador.Importar_cotizaciones()
importador.cotizaciones[:3]
indicadores = Indicadores(importador)
indicadores.dibujar_grafico()
The script that works outside the class is:
# Usando plotly.express
from plotly.offline import iplot
import plotly.express as px
start = "2000-1-4"
end = date.today()
aux_val_ind = importador.cotizaciones[["Iberdrola", "Ibex35"]].pct_change().dropna()
df = aux_val_ind.copy(deep=True)
df['Media'] = df.mean(axis = 1)
px.line((df + 1).cumprod() ,y=df.columns ,title=f"\nValor actual de 1€ invertido el {start} ")
Only one issue, you missed to return the figure.
class Indicadores:
def __init__(self, importador):
self.importador = importador
def dibujar_grafico(self):
self.aux_val_ind = importador.cotizaciones[["Iberdrola", "Ibex35"]].pct_change().dropna()
df = self.aux_val_ind.copy(deep=True)
df['Media'] = df.mean(axis = 1)
# Usando plotly.express
return px.line((df + 1).cumprod() ,y=df.columns ,title=f"\nValor de 1€ invertido desde el { importador.start} hasta el {importador.end} ")

Not getting the Multithreaading to work for GTK 3 python

I am trying to get the themes from the gnome-look.org and trying to create widgets by scraping the website.
I wanted to show the window first while updating the GtkWidgets necessary in the background via another Thread.
Here is my code
[code]
#!/usr/bin/python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf
import requests
import sys
import gi
import shutil
from bs4 import BeautifulSoup
import dryscrape
import json
import urllib.parse
import concurrent.futures
import threading
class ReadGnomeLook:
def format_bytes(self, size):
# 2**10 = 1024
power = 2**10
n = 0
power_labels = {0 : '', 1: 'KB', 2: 'MB', 3: 'GB'}
while size > power:
size /= power
n += 1
return str("{:.2f}".format(size)) +' ' + str(power_labels[n])
def getDownloadLinks(self, childURL):
#childURL = "https://www.gnome-look.org/s/Gnome/p/1519633"
childURL = childURL+"#files-panel"
session = dryscrape.Session()
session.set_attribute('auto_load_images', False)
session.visit(childURL)
response = session.body()
soup = BeautifulSoup(response, features='lxml')
downloadlink = []
allscripts = soup.find_all('script', {"src":False})
for each_script in range(len(allscripts)):
content = str(allscripts[each_script]).split("var")
for indx in content:
if 'filesJson' in str(indx):
content = indx.replace('filesJson = ','').replace(';','')
content = json.loads(content)
links = []
for each_item in content:
if each_item['active'] == '1':
links.append({'name':each_item['name'],'type':each_item['type'],'size':format_bytes(int(each_item['size'])),'md5sum':each_item['md5sum'],'title':each_item['title'],'description':each_item['description'],'url':urllib.parse.unquote(each_item['url'])})
for each in links:
downloadlink.append(each)
return downloadlink
def readWebpage(self, URL):
myProducts = []
baseURL="https://www.gnome-look.org"
#URL = "https://www.gnome-look.org/browse/cat/132/order/latest/"
session = dryscrape.Session()
session.set_header('Host','www.gnome-look.org')
session.visit(URL)
response = session.body()
soup = BeautifulSoup(response, features='lxml')
#print(soup)
#soup.find(class="product-browse-item-info")
mydivs = soup.find_all("div", {"class": "product-browse-item picture"})
for mydiv in mydivs:
myProducts.append([
{'name' : mydiv.div.a.findAll("div",{"class":"product-browse-item-info"})[0].h2.text},
{'category' : mydiv.div.a.findAll("div",{"class":"product-browse-item-info"})[0].findAll("span")[0].text},
{'author' : mydiv.div.a.findAll("div",{"class":"product-browse-item-info"})[0].findAll("span")[1].b.text},
{'img' : mydiv.div.a.div.img['src']},
{'href' : mydiv.div.a['href']}
])
productCatalog = []
for elements in myProducts:
productCatalog.append([
{
'Name':elements[0]['name'],
'Category': elements[1]['category'],
'Author': elements[2]['author'],
'Image': elements[3]['img'],
'Link': baseURL + elements[4]['href'],
#'DownloadLinks': getDownloadLinks(baseURL + elements[4]['href'])
}
])
return productCatalog
class AppicationWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Themes Manager")
# Main Application Window
# self.set_title("Themes Manager v1.0")
#self.set_default_size(400, 400)
self.set_position(Gtk.WindowPosition.CENTER)
self.connect("destroy",Gtk.main_quit)
# Create Image and Title Grid
#self.image = self.getImageFromWeb('https://media.wired.com/photos/592697678d4ebc5ab806acf7/master/w_2560%2Cc_limit/GooglePlay.jpg')
#self.image.set_from_file("android-download.png")
#image.set_size(200,200)
print("Before 1st Show all")
self.show_all()
z = threading.Thread(target=self.doProcessing(),daemon=True)
z.start()
print("Started Z thread")
def doProcessing(self):
# Grid for Full Icon Themes
self.gridfulliconthemes = Gtk.FlowBox(valign = Gtk.Align.START)
self.gridfulliconthemesscroll = Gtk.ScrolledWindow(hexpand=True, vexpand=True) # Create scroll window
self.gridfulliconthemesscroll.add(self.gridfulliconthemes) # Adds the TreeView to the scroll container
self.getProductCatalog()
## Start
self.URLs = []
self.labels = []
self.images = []
self.threads = []
for each_item in self.productCatalog:
image = Gtk.Image()
image.new_from_file('/tmp/82682596e6c89475b2f21221d5dc61927887.png')
self.images.append(image)
self.labels.append(Gtk.Label("loading"))
for each_item in range(0,len(self.productCatalog)):
#print(each_item[0]['Name'])
self.URLs.append(self.productCatalog[each_item][0]['Image'])
vertical_box = Gtk.Box()
vertical_box.set_homogeneous(True)
vertical_items = Gtk.FlowBox(valign = Gtk.Align.START)
vertical_items.set_max_children_per_line(1)
label = Gtk.Label()
label.set_text(self.productCatalog[each_item][0]['Name'])
label.set_line_wrap(True)
label.set_max_width_chars(10)
label.set_hexpand(True)
self.labels.append(label)
#image = Gtk.Image()
#self.images.append(image)
vertical_items.add(self.images[each_item])
vertical_items.add(self.labels[each_item])
vertical_box.add(vertical_items)
vertical_box.connect("button-press-event", self.do_anything)
self.gridfulliconthemes.add(vertical_box)
## End
# Create Notebook to add to the Window
self.notebook = Gtk.Notebook()
self.add(self.notebook)
self.fullicontheme = Gtk.Label()
self.fullicontheme.set_text("Full Icon Themes")
self.gtkthemes = Gtk.Label()
self.gtkthemes.set_text("Gtk 3/4 Themes")
self.gnomeshellthemes = Gtk.Label()
self.gnomeshellthemes.set_text("Gnome Shell Themes")
self.fulliconthemepage = Gtk.Label()
self.fulliconthemepage.set_text("Full Icon Themes Page")
self.gtkthemespage = Gtk.Label()
self.gtkthemespage.set_text("GTK themes Page")
self.gnomeshellthemespage = Gtk.Label()
self.gnomeshellthemespage.set_text("Gnome Shell Themes Page")
#notebook.append_page(fullicontheme, Gtk.Label("Icon Page"))
self.notebook.append_page(self.gridfulliconthemesscroll, self.fulliconthemepage)
self.notebook.append_page(self.gtkthemes, self.gtkthemespage)
self.notebook.append_page(self.gnomeshellthemes, self.gnomeshellthemespage)
self.notebook.set_tab_reorderable(self.gridfulliconthemesscroll, True)
#self.add(hb)
#self.show_all()
#threadtemp = threading.Thread(target=self.getImageFromWeb(each_item[0]['Image']))
#self.threads.append(threadtemp)
#self.getAllImages()
x = threading.Thread(target=self.getAllImages(),daemon=True)
x.start()
self.show_all()
def getProductCatalog(self):
# Download Links from GnomeLook.org
URL = "https://www.gnome-look.org/s/Gnome/browse/cat/132/page/2/ord/latest/"
readgnomelook = ReadGnomeLook()
self.productCatalog = readgnomelook.readWebpage(URL)
#print(json.dumps(productCatalog, sort_keys=False, indent=4))
def getAllImages(self):
for i in range(0,len(self.productCatalog)):
#self.images.append(self.getImageFromWeb(self.productCatalog[i][0]['Image']))
#self.images[i] = self.getImageFromWeb(self.productCatalog[i][0]['Image'],self.images[i])
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
future = executor.submit(self.getImageFromWeb, self.productCatalog[i][0]['Image'], self.images[i])
# #self.images.append(future.result())
self.images[i]= future.result()
# #print(type(self.images[i]))
def do_anything(self):
print("clicked on box")
def getImageFromWeb(self, URL,image):
filename = '/tmp/'+URL.split("/")[-1]
try:
f = open(filename)
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
filename=filename,
width=100,
height=100,
preserve_aspect_ratio=False)
Gtk.Image.set_from_pixbuf(image, pixbuf)
#image.set_from_file(filename)
#print("Got the image : " + filename)
#del r
return image
except IOError:
#print("File not accessible")
r = requests.get(URL,stream=True)
if r.status_code == 200:
with open(filename,'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
filename=filename,
width=200,
height=200,
preserve_aspect_ratio=False)
Gtk.Image.set_from_pixbuf(image, pixbuf)
#image.set_from_file(filename)
#print("Got the image : " + filename)
return image
else:
#print("Failed to get the image : " + filename)
return None
del r
window = AppicationWindow()
#window.connect("destroy",Gtk.main_quit)
#window.show_all()
Gtk.main()
[/code]
Code works fine. But in below code, the thread doProcessing() is getting completed and then I am seeing the "Started Z thread"
print("Before 1st Show all")
self.show_all()
z = threading.Thread(target=self.doProcessing(),daemon=True)
z.start()
print("Started Z thread")
As I see, doProcessing should start in background and "Started Z thread" should be printed immediately but that's not happening.
Am I missing anything here ? Any help is appreciated.
Thanks, Debasish
z = threading.Thread(target=self.doProcessing(),daemon=True)
threading.Thread wants a function not the result of a function, thus try:
z = threading.Thread(target=self.doProcessing,daemon=True)

Refresh QMainWindow with different QMainWindow in Pyqt4

I need your help to solve this problem, I want to refresh a QlistWidget in pyqt4 when I add a new register from another QMainWindow not in the principal, i tried with "repaint()" but it doesn´t work, to understand it better I post the code
This is the main window where I added all items from a DB
class Psicologo(QMainWindow):
def __init__(self, parent=None):
super(Psicologo, self).__init__(parent)
uic.loadUi('inicio.ui', self)
self.button_volver.clicked.connect(self.regresar)
self.button_nvo_psicologo.clicked.connect(self.nuevoPsicologo)
query = "SELECT * FROM user"
cursor, conexion = CreateConexion()
cursor.execute(query)
registro = cursor.fetchall()
for i in registro:
self.lista_psicologos.addItem(i[1]+" "+i[2]+" "+i[3])
def regresar(self):
self.parent().show()
self.close()
def nuevoPsicologo(self):
self.hide()
nuevo_form = AltaPsico(self)
nuevo_form.show()
And here is the other window where I create a new register
class AltaPsico(QMainWindow):
def __init__(self, parent=None):
super(AltaPsico, self).__init__(parent)
uic.loadUi('alta_paciente.ui', self)
self.combo_sexo.hide()
self.label_12.hide()
self.text_comentario.hide()
self.label_14.hide()
self.line_correo_2.hide()
self.label_13.hide()
self.button_volver.clicked.connect(self.regresar)
self.button_guardar.clicked.connect(self.guardar)
self.button_eliminar.hide()
def guardar(self):
nombre = self.line_nombre.text()
app = self.line_app.text()
apm = self.line_apm.text()
domicilio = self.line_domicilio.text()
edad = self.line_edad.text()
telefono = self.line_telefono.text()
especialidad = self.line_especialidad.text()
correo = self.line_correo.text()
usuario = self.line_usuario.text()
password = self.line_password.text()
pass2 = self.line_password_2.text()
if password == pass2:
if edad.isdigit():
if validate_email(correo):
if telefono.isdigit():
query = "INSERT INTO user(idUser, Nombre, ApPaterno, ApMaterno, Domicilio, Edad, Telefono, Especialidad, Correo, Usuario, Password, Tipo) VALUES (0,'"+nombre+"','"+app+"', '"+apm+"', '"+domicilio+"', '"+edad+"', '"+telefono+"', '"+especialidad+"', '"+correo+"', '"+usuario+"', '"+password+"', 2);"
print (query)
cursor, conexion = CreateConexion()
cursor.execute(query)
msgBoxCancel = QtGui.QMessageBox( self )
msgBoxCancel.setIcon( QtGui.QMessageBox.Information )
msgBoxCancel.setText( "Usuario registrado con exito" )
msgBoxCancel.addButton( QtGui.QMessageBox.Ok )
msgBoxCancel.exec_()
conexion.commit()
conexion.close()
self.parent().show()
self.QMainWindow.update()
self.close()
else:
msgBoxCancel = QtGui.QMessageBox( self )
msgBoxCancel.setIcon( QtGui.QMessageBox.Information )
msgBoxCancel.setText( "¡Telefono invalido, ingrese telefono valido!" )
msgBoxCancel.addButton( QtGui.QMessageBox.Ok )
msgBoxCancel.exec_()
else:
msgBoxCancel = QtGui.QMessageBox( self )
msgBoxCancel.setIcon( QtGui.QMessageBox.Information )
msgBoxCancel.setText( "¡Correo invalido, ingrese correo valido!" )
msgBoxCancel.addButton( QtGui.QMessageBox.Ok )
msgBoxCancel.exec_()
else:
msgBoxCancel = QtGui.QMessageBox( self )
msgBoxCancel.setIcon( QtGui.QMessageBox.Information )
msgBoxCancel.setText( "¡Ingrese una edad valida!" )
msgBoxCancel.addButton( QtGui.QMessageBox.Ok )
msgBoxCancel.exec_()
else:
msgBoxCancel = QtGui.QMessageBox( self )
msgBoxCancel.setIcon( QtGui.QMessageBox.Information )
msgBoxCancel.setText( "¡La contraseña no coincide, intentelo de nuevo!" )
msgBoxCancel.addButton( QtGui.QMessageBox.Ok )
msgBoxCancel.exec_()
def regresar(self):
self.parent().repaint()
self.parent().show()
self.close()
When the register ends succesfully this window closes automatically but when the principal shows again the listWidget shows the same registers at the begin.
I hope this community can help me, i´ve been searching about this topic but i can´t find anything.
If the database is modified, the GUI is not notified so the data must be requested again:
class Psicologo(QMainWindow):
def __init__(self, parent=None):
super(Psicologo, self).__init__(parent)
uic.loadUi('inicio.ui', self)
self.button_volver.clicked.connect(self.regresar)
self.button_nvo_psicologo.clicked.connect(self.nuevoPsicologo)
self.load_from_db()
def load_from_db(self):
self.lista_psicologos.clear()
query = "SELECT * FROM user"
cursor, conexion = CreateConexion()
cursor.execute(query)
registro = cursor.fetchall()
for i in registro:
self.lista_psicologos.addItem("{} {} {}".format(i[1], i[2], i[3]))
def regresar(self):
self.parent().show()
self.close()
def nuevoPsicologo(self):
self.hide()
nuevo_form = AltaPsico(self)
nuevo_form.show()
def guardar(self):
# ...
conexion.commit()
conexion.close()
self.parent().show()
self.parent().load_from_db()

Export seen items in QTreeView

I have a new question, I am designing an application and I don not know how to export items to an excel file, in the code I use a QTreeView with a QSortFilteredProxyModel, and I include a filter for text written in a QLineEdit, I need to export all of the items than can be seen after being filtered. But, how can i take or add those items to a list, for exporting them to an excel file?
if anyone can help me I would be so grateful.
sry my bad english
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from dbFacades.profitFacade import ProfitFacade
class MainTabProfits(QGridLayout):
def __init__(self):
super(MainTabProfits, self).__init__()
self.screen = QDesktopWidget().screenGeometry()
self.profitList = ProfitFacade().allProfit()
self.addWidget(self.topGroupBox(),0,0,1,4)
self.addWidget(self.rightGroupBox(), 1, 0,1,4)
self.addWidget(self.botGroupBox(),2,3)
# -----------------------------------------------------
# Se define el grupo superior
def topGroupBox(self):
groupBox = QGroupBox()
groupBox.setTitle("Busqueda")
self.lineEdit1 = QLineEdit()
self.lineEdit1.setPlaceholderText("Ingrese una fecha con el siguiente formato -> dd/mm/aaaa")
self.lineEdit1.textChanged.connect(self.filterRegExpChanged)
self.lineEdit1.textChanged.connect(self.setSlashChanged)
self.lineEdit1.setMaxLength(10)
leftLayout = QHBoxLayout()
leftLayout.addWidget(self.lineEdit1)
leftLayout.stretch(1)
leftGroupBox = QGroupBox("Fecha Exacta")
leftGroupBox.setLayout(leftLayout)
hBoxLayout = QHBoxLayout()
hBoxLayout.addWidget(leftGroupBox)
groupBox.setLayout(hBoxLayout)
return groupBox
# -----------------------------------------------------
# Se define el grupo principal(izquierdo) de contenido
def rightGroupBox(self):
groupBox = QGroupBox()
groupBox.setTitle("Control de Finanzas y busqueda")
self.setHeaders()
self.proxyModel = QSortFilterProxyModel()
self.proxyModel.setDynamicSortFilter(True)
self.proxyModel.setSourceModel(self.model)
self.proxyModel.setFilterKeyColumn(0)
self.treeView = QTreeView()
self.treeView.setRootIsDecorated(False)
self.treeView.setAlternatingRowColors(True)
self.treeView.setModel(self.proxyModel)
self.treeView.setSortingEnabled(True)
self.treeView.sortByColumn(0, Qt.AscendingOrder)
self.treeView.resizeColumnToContents(0)
self.treeView.setEditTriggers(QTreeView.NoEditTriggers)
vBoxLayout = QVBoxLayout()
vBoxLayout.addWidget(self.treeView)
groupBox.setLayout(vBoxLayout)
self.setProfit()
return groupBox
def botGroupBox(self):
groupBox = QGroupBox()
groupBox.setTitle("Exportacion")
self.radioButton0 = QRadioButton("*.PDF")
self.radioButton0.setIcon(QIcon("icons/pdf.png"))
self.radioButton0.setIconSize(QSize(self.screen.width() / 50, self.screen.width() / 50))
self.radioButton1 = QRadioButton("*.Excel")
self.radioButton1.setIcon(QIcon("icons/excel.png"))
self.radioButton1.setIconSize(QSize(self.screen.width() / 50, self.screen.width() / 50))
pushButton = QPushButton(QIcon("icons/export.png"),"Exportar")
pushButton.released.connect(self.exportList)
pushButton.setIconSize(QSize(self.screen.width() / 50, self.screen.width() / 50))
hBoxLayout = QHBoxLayout()
hBoxLayout.addWidget(self.radioButton0)
hBoxLayout.addWidget(self.radioButton1)
hBoxLayout.addWidget(pushButton)
hBoxLayout.stretch(1)
groupBox.setLayout(hBoxLayout)
return groupBox
# ------------------------------------------------------
# ZONA METODOS
# Metodo que define las cabezeras del menu y crea el model
def setHeaders(self):
self.model = QStandardItemModel(0, 5, self)
self.model.setHeaderData(0, Qt.Horizontal, "Fecha")
self.model.setHeaderData(1, Qt.Horizontal, "Monto")
self.model.setHeaderData(2, Qt.Horizontal, "Mesa")
self.model.setHeaderData(3, Qt.Horizontal, "Tipo de Pago")
self.model.setHeaderData(4, Qt.Horizontal, "Codigo Operacion")
# Metodo para filtrar por texto escrito en line edit
def filterRegExpChanged(self):
regExp = QRegExp(self.lineEdit1.text(), Qt.CaseInsensitive)
self.proxyModel.setFilterRegExp(regExp)
# Metodo para el formato de fecha en LineEdit1
def setSlashChanged(self):
text = self.lineEdit1.text()
if(len(text)==2):
self.lineEdit1.setText(text+"-")
elif(len(text)==5):
self.lineEdit1.setText(text+"-")
self.lineEdit2.setText("")
self.lineEdit3.setText("")
# Metodo para el formato de fecha en lineEdit2 y 2
def inRangeChanged(self):
text = self.lineEdit2.text()
text1 = self.lineEdit3.text()
if(len(text)==2):
self.lineEdit2.setText(text+"-")
elif(len(text)==5):
self.lineEdit2.setText(text+"-")
elif(len(text1)==2):
self.lineEdit3.setText(text1+"-")
elif(len(text1)==5):
self.lineEdit3.setText(text1+"-")
self.lineEdit1.setText("")
# --------------------------------------------------------------------------------
# Metodo que establece los datos en la lista
def setProfit(self):
for profit in self.profitList:
self.model.insertRow(0)
self.model.setData(self.model.index(0,0), profit[0])
self.model.setData(self.model.index(0,1), profit[1])
self.model.setData(self.model.index(0,2), profit[2])
self.model.setData(self.model.index(0,3), profit[3])
self.model.setData(self.model.index(0,4), profit[4])
# --------------------------------------------------------------------------------
# Metodo para exportar a excel
def exportList(self):
if self.radioButton0.isChecked():
pass
if self.radioButton1.isChecked():
HERE I WANT EXPORT ITEMS FILTERED
HERE I WANT EXPORT ITEMS FILTERED
HERE I WANT EXPORT ITEMS FILTERED
HERE I WANT EXPORT ITEMS FILTERED
You can use the fallowing functions from QSortFilterProxyModel:
rowCount(), columnCount() and index(), and then use the returned index to get the data:
rowCnt = self.proxyModel.rowCount()
colCnt = self.proxyModel.columnCount()
for row in range(0, rowCnt):
for col in range(0, colCnt):
modelIndex = self.proxyModel.index(row, col)
print modelIndex.data().toString()

Python 3: QString on PyQt4

I'm having a problem trying to do a very simple user interface. I made my UI with Qt Designer, and then with pyuic4 I got my python code. Then I programmed the function I needed, and compiled with Eclipse IDE.
The code I got from pyuic4 is:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Dni.ui'
#
# Created: Sat Apr 14 02:44:34 2012
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(371, 217)
Dialog.setMinimumSize(QtCore.QSize(371, 217))
self.layoutWidget = QtGui.QWidget(Dialog)
self.layoutWidget.setGeometry(QtCore.QRect(30, 30, 311, 151))
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.gridLayout = QtGui.QGridLayout(self.layoutWidget)
self.gridLayout.setMargin(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(self.layoutWidget)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.entrada = QtGui.QLineEdit(self.layoutWidget)
self.entrada.setObjectName(_fromUtf8("entrada"))
self.horizontalLayout.addWidget(self.entrada)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.boton = QtGui.QPushButton(self.layoutWidget)
self.boton.setObjectName(_fromUtf8("boton"))
self.gridLayout.addWidget(self.boton, 1, 0, 1, 1)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_3 = QtGui.QLabel(self.layoutWidget)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_2.addWidget(self.label_3)
self.salida = QtGui.QLineEdit(self.layoutWidget)
self.salida.setObjectName(_fromUtf8("salida"))
self.horizontalLayout_2.addWidget(self.salida)
self.gridLayout.addLayout(self.horizontalLayout_2, 2, 0, 1, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "Introduzca su DNI", None, QtGui.QApplication.UnicodeUTF8))
self.boton.setText(QtGui.QApplication.translate("Dialog", "Hallar NIF", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Dialog", "NIF:", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
And the code I made with the function I need:
from Dni import Ui_Dialog
from PyQt4 import QtCore, QtGui
LETRADNI = {0:'T', 1:'R', 2:'W', 3:'A', 4:'G', 5:'M', 6:'Y', 7:'F', 8:'P', 9:'D', 10:'X', 11:'B', 12:'N',
13: 'J', 14:'Z', 15:'S', 16:'Q', 17:'V', 18:'H', 19:'L', 20:'C', 21:'K', 22:'E'}
# Se hereda de la clase QtGui.QMainWindow
class Principal(QtGui.QMainWindow):
# Se define el constructor de la clase __init__
def __init__(self):
# Se llama al constructor de la clase padre
QtGui.QMainWindow.__init__(self)
# Se crea la instancia de Ui_Dialog
self.ventana = Ui_Dialog()
self.ventana.setupUi(self)
# Se conectan las señales con los slots
self.connect(self.ventana.boton,QtCore.SIGNAL('clicked()'), self.letradni)
def Calcula_letra_dni(dni):
'''Función Calcula_letra_dni:
Funcionamiento:
La función recibe el valor entero dni. Posteriormente calculará el resto de la división
por 23. Éste número se buscará en el diccionario 'LETRADNI' para obtener la letra correspondiente
a ese DNI.
Argumentos
dni -- número del documento nacional de identidad (int)
Devuelve:
Una cadena (string) -- DNI + letra preparado para salida por pantalla
'''
#if len(str(dni))>8 & len(str(dni))<7:
# raise ValueError('El dni debe tener entre 7 y 8 cifras')
num_letra = dni % 23.0
letra = LETRADNI[num_letra]
return '{0}-{1}'.format(dni,letra)
def letradni(self):
self.ventana.salida.setText(Calcula_letra_dni(self.ventana.entrada.text()))
The first one compiles and runs, it shows my ui perfectly.
Compiling the second one I get an error that says:
Description Resource Path Location Type
Undefined variable from import: QString Dni.py /Dni line 18 PyDev Problem
Can anyone help me?
Thanks in advance.
First off, I think your actual listed problem is related to Eclipse, pydev, and your projects PYTHONPATH. Review this to make sure you have properly set up everything and included PyQt4 in your pythonpath:
http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application/
After that, you seem to have some problems with your code beyond what you have mentioned...
First you define Principal class, then a Calcula_letra_dni function, but then you are defining what looks like a class instance method letradni which should be part of Principal:
class Principal(QtGui.QMainWindow):
# Se define el constructor de la clase __init__
def __init__(self):
...
def letradni(self):
...
def Calcula_letra_dni(dni):
...
Then it looks like you will raise an exception when you try to do math on a string (thanks #Avaris) and float:
num_letra = dni % 23.0
You should probably convert that string to a float first: num_letra = float(dni) % 23.0
And finally, I think you also forgot to define a main for your application. You have the one that is autogenerated in your Dni.py, but you didn't write one for your actual entry point script:
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
form = Principal()
form.show()
sys.exit(app.exec_())

Resources