How to see my data in model /view qml with pyqt5
I want to see my data in my QmL GUI thanks to model/view programming!
I take my data from mysql, with mysql.connector
i don't understand very well the model/view, i understand the model/view concept but, coding it, is hard! Please help me with my code give me a solution I am a french-speaking so excuse me for my mistakes in english
#Main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#ligne d'importation des classes necessaire
import sys
from PyQt5.QtCore import QObject
class MainApp(QObject):
def __init__(self, context, parent=None):
super(MainApp, self).__init__(parent)
self.win = parent
self.ctx = context
def Insert(self):
nom = self.win.findChild(QObject, "nName").property("text")
prenom = self.win.findChild(QObject, "nFirstname").property("text")
self.win.findChild(QObject, "LOB").setProperty("text","cliqué")
# insert(nom,prenom)
return 0
SqlFunc.py
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="agenda"
)
mycursor = mydb.cursor()
def insert(nom,prenom):
var=0
sql = "INSERT INTO contact (numero, nom) VALUES (%s, %s)"
val = (nom, prenom)
if mycursor.execute(sql, val):
mydb.commit()
return "Enregistrement effectué"
else:
return "Echec de l'enregistrement contact déjà enregistré!"
def select():
mycursor.execute("SELECT * FROM contact")
data_from = mycursor.fetchall()
if data_from == "":
return "Aucun contact enregistré"
else:
return data_from
def search(name):
mycursor.execute("SELECT contact.numero, contact.nom WHERE
contact.nom LIKE '%{}%' ORDER BY contact.nom".format(name))
myresult = mycursor.fetchall()
return myresult
def update(old_address,new_address):
sql_request = "UPDATE customers SET address = %s WHERE address = %s"
valors = (old_address, new_address)
if mycursor.execute( sql_request, valors):
mydb.commit()
return "Modification effectuer avec succes"
else:
return "Echec de la modification"
def delete(address):
sql_request = "DELETE FROM customers WHERE address = %s"
func_address = (address)
if mycursor.execute(sql_request,func_address):
mydb.commit()
return "Suppression effectuée"
else:
return "Echec de la suppression"
databases.py
import SqlFunc
class DataBase():
def __int__(self):
self.data_from_databases
@staticmethod
def take_from_mysql():
data_to_model = SqlFunc.select()
return data_to_model
@staticmethod
def search_by_name(contact_name):
search_result = SqlFunc.search(contact_name)
return search_result
@staticmethod
def update_valor(old,new):
update_result = SqlFunc.update(old,new)
return update_result
@staticmethod
def delete_valor(address):
delete_result = SqlFunc.delete(address)
return delete_result
Star_app.py
import sys, Modele,databases
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
from os import system
try:
system('start
C:\Users\yyy\PycharmProjects\TEST_CEI_GUI\mysql\bin\mysqld.exe')
except:
quit()
else:
from Main import MainApp
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
engine.load('C:\UsersyyyPycharmProjectsTEST_CEI_GUIGO7\
main.qml')
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
ctx.setContextProperty("myModel", model)
win.show()
sys.exit(app.exec())
Modele.py
class NewModel(QAbstractListModel):
numero_role = Qt.UserRole + 1
nom_role = Qt.UserRole + 2
_roles = {numero_role: b"numero", nom_role: b"nom"}
def __init__(self):
super(NewModel, self).__init__()
self._contact =
self._data = databases.DataBase().take_from_mysql()
def update(self,search_term):
self.beginResetModel()
self._contact = self._data.search_by_name(search_term)
self.endResetModel()
@pyqtSlot(str)
def search_input(self,searh_input):
if len(searh_input) > 3:
print(searh_input)
self.update(searh_input)
def rowCount(self, parent=None, *args, **kwargs):
return len(self._data)
def data(self, QModelIndex, role=None):
row = QModelIndex.row()
if role == self.numero_role:
return self._data[row]["numero"]
if role == self.nom_role:
return self._data[row]["nom"]
def roleNames(self):
return self._roles
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
Page {
width: 600
height: 400
clip: true
contentHeight: 20
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom//
}
}
}
}
my GUI crashes after execution, and when I modify code nothing is displayed with my view
python python-3.x pyqt qml pyqt5
add a comment |
I want to see my data in my QmL GUI thanks to model/view programming!
I take my data from mysql, with mysql.connector
i don't understand very well the model/view, i understand the model/view concept but, coding it, is hard! Please help me with my code give me a solution I am a french-speaking so excuse me for my mistakes in english
#Main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#ligne d'importation des classes necessaire
import sys
from PyQt5.QtCore import QObject
class MainApp(QObject):
def __init__(self, context, parent=None):
super(MainApp, self).__init__(parent)
self.win = parent
self.ctx = context
def Insert(self):
nom = self.win.findChild(QObject, "nName").property("text")
prenom = self.win.findChild(QObject, "nFirstname").property("text")
self.win.findChild(QObject, "LOB").setProperty("text","cliqué")
# insert(nom,prenom)
return 0
SqlFunc.py
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="agenda"
)
mycursor = mydb.cursor()
def insert(nom,prenom):
var=0
sql = "INSERT INTO contact (numero, nom) VALUES (%s, %s)"
val = (nom, prenom)
if mycursor.execute(sql, val):
mydb.commit()
return "Enregistrement effectué"
else:
return "Echec de l'enregistrement contact déjà enregistré!"
def select():
mycursor.execute("SELECT * FROM contact")
data_from = mycursor.fetchall()
if data_from == "":
return "Aucun contact enregistré"
else:
return data_from
def search(name):
mycursor.execute("SELECT contact.numero, contact.nom WHERE
contact.nom LIKE '%{}%' ORDER BY contact.nom".format(name))
myresult = mycursor.fetchall()
return myresult
def update(old_address,new_address):
sql_request = "UPDATE customers SET address = %s WHERE address = %s"
valors = (old_address, new_address)
if mycursor.execute( sql_request, valors):
mydb.commit()
return "Modification effectuer avec succes"
else:
return "Echec de la modification"
def delete(address):
sql_request = "DELETE FROM customers WHERE address = %s"
func_address = (address)
if mycursor.execute(sql_request,func_address):
mydb.commit()
return "Suppression effectuée"
else:
return "Echec de la suppression"
databases.py
import SqlFunc
class DataBase():
def __int__(self):
self.data_from_databases
@staticmethod
def take_from_mysql():
data_to_model = SqlFunc.select()
return data_to_model
@staticmethod
def search_by_name(contact_name):
search_result = SqlFunc.search(contact_name)
return search_result
@staticmethod
def update_valor(old,new):
update_result = SqlFunc.update(old,new)
return update_result
@staticmethod
def delete_valor(address):
delete_result = SqlFunc.delete(address)
return delete_result
Star_app.py
import sys, Modele,databases
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
from os import system
try:
system('start
C:\Users\yyy\PycharmProjects\TEST_CEI_GUI\mysql\bin\mysqld.exe')
except:
quit()
else:
from Main import MainApp
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
engine.load('C:\UsersyyyPycharmProjectsTEST_CEI_GUIGO7\
main.qml')
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
ctx.setContextProperty("myModel", model)
win.show()
sys.exit(app.exec())
Modele.py
class NewModel(QAbstractListModel):
numero_role = Qt.UserRole + 1
nom_role = Qt.UserRole + 2
_roles = {numero_role: b"numero", nom_role: b"nom"}
def __init__(self):
super(NewModel, self).__init__()
self._contact =
self._data = databases.DataBase().take_from_mysql()
def update(self,search_term):
self.beginResetModel()
self._contact = self._data.search_by_name(search_term)
self.endResetModel()
@pyqtSlot(str)
def search_input(self,searh_input):
if len(searh_input) > 3:
print(searh_input)
self.update(searh_input)
def rowCount(self, parent=None, *args, **kwargs):
return len(self._data)
def data(self, QModelIndex, role=None):
row = QModelIndex.row()
if role == self.numero_role:
return self._data[row]["numero"]
if role == self.nom_role:
return self._data[row]["nom"]
def roleNames(self):
return self._roles
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
Page {
width: 600
height: 400
clip: true
contentHeight: 20
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom//
}
}
}
}
my GUI crashes after execution, and when I modify code nothing is displayed with my view
python python-3.x pyqt qml pyqt5
You could show the fields in your table contact
– eyllanesc
Jan 19 at 20:38
movectx.setContextProperty("py_MainApp", py_mainapp) ctx.setContextProperty("myModel", model)
beforeengine.load(...)
– eyllanesc
Jan 19 at 22:14
add a comment |
I want to see my data in my QmL GUI thanks to model/view programming!
I take my data from mysql, with mysql.connector
i don't understand very well the model/view, i understand the model/view concept but, coding it, is hard! Please help me with my code give me a solution I am a french-speaking so excuse me for my mistakes in english
#Main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#ligne d'importation des classes necessaire
import sys
from PyQt5.QtCore import QObject
class MainApp(QObject):
def __init__(self, context, parent=None):
super(MainApp, self).__init__(parent)
self.win = parent
self.ctx = context
def Insert(self):
nom = self.win.findChild(QObject, "nName").property("text")
prenom = self.win.findChild(QObject, "nFirstname").property("text")
self.win.findChild(QObject, "LOB").setProperty("text","cliqué")
# insert(nom,prenom)
return 0
SqlFunc.py
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="agenda"
)
mycursor = mydb.cursor()
def insert(nom,prenom):
var=0
sql = "INSERT INTO contact (numero, nom) VALUES (%s, %s)"
val = (nom, prenom)
if mycursor.execute(sql, val):
mydb.commit()
return "Enregistrement effectué"
else:
return "Echec de l'enregistrement contact déjà enregistré!"
def select():
mycursor.execute("SELECT * FROM contact")
data_from = mycursor.fetchall()
if data_from == "":
return "Aucun contact enregistré"
else:
return data_from
def search(name):
mycursor.execute("SELECT contact.numero, contact.nom WHERE
contact.nom LIKE '%{}%' ORDER BY contact.nom".format(name))
myresult = mycursor.fetchall()
return myresult
def update(old_address,new_address):
sql_request = "UPDATE customers SET address = %s WHERE address = %s"
valors = (old_address, new_address)
if mycursor.execute( sql_request, valors):
mydb.commit()
return "Modification effectuer avec succes"
else:
return "Echec de la modification"
def delete(address):
sql_request = "DELETE FROM customers WHERE address = %s"
func_address = (address)
if mycursor.execute(sql_request,func_address):
mydb.commit()
return "Suppression effectuée"
else:
return "Echec de la suppression"
databases.py
import SqlFunc
class DataBase():
def __int__(self):
self.data_from_databases
@staticmethod
def take_from_mysql():
data_to_model = SqlFunc.select()
return data_to_model
@staticmethod
def search_by_name(contact_name):
search_result = SqlFunc.search(contact_name)
return search_result
@staticmethod
def update_valor(old,new):
update_result = SqlFunc.update(old,new)
return update_result
@staticmethod
def delete_valor(address):
delete_result = SqlFunc.delete(address)
return delete_result
Star_app.py
import sys, Modele,databases
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
from os import system
try:
system('start
C:\Users\yyy\PycharmProjects\TEST_CEI_GUI\mysql\bin\mysqld.exe')
except:
quit()
else:
from Main import MainApp
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
engine.load('C:\UsersyyyPycharmProjectsTEST_CEI_GUIGO7\
main.qml')
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
ctx.setContextProperty("myModel", model)
win.show()
sys.exit(app.exec())
Modele.py
class NewModel(QAbstractListModel):
numero_role = Qt.UserRole + 1
nom_role = Qt.UserRole + 2
_roles = {numero_role: b"numero", nom_role: b"nom"}
def __init__(self):
super(NewModel, self).__init__()
self._contact =
self._data = databases.DataBase().take_from_mysql()
def update(self,search_term):
self.beginResetModel()
self._contact = self._data.search_by_name(search_term)
self.endResetModel()
@pyqtSlot(str)
def search_input(self,searh_input):
if len(searh_input) > 3:
print(searh_input)
self.update(searh_input)
def rowCount(self, parent=None, *args, **kwargs):
return len(self._data)
def data(self, QModelIndex, role=None):
row = QModelIndex.row()
if role == self.numero_role:
return self._data[row]["numero"]
if role == self.nom_role:
return self._data[row]["nom"]
def roleNames(self):
return self._roles
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
Page {
width: 600
height: 400
clip: true
contentHeight: 20
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom//
}
}
}
}
my GUI crashes after execution, and when I modify code nothing is displayed with my view
python python-3.x pyqt qml pyqt5
I want to see my data in my QmL GUI thanks to model/view programming!
I take my data from mysql, with mysql.connector
i don't understand very well the model/view, i understand the model/view concept but, coding it, is hard! Please help me with my code give me a solution I am a french-speaking so excuse me for my mistakes in english
#Main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#ligne d'importation des classes necessaire
import sys
from PyQt5.QtCore import QObject
class MainApp(QObject):
def __init__(self, context, parent=None):
super(MainApp, self).__init__(parent)
self.win = parent
self.ctx = context
def Insert(self):
nom = self.win.findChild(QObject, "nName").property("text")
prenom = self.win.findChild(QObject, "nFirstname").property("text")
self.win.findChild(QObject, "LOB").setProperty("text","cliqué")
# insert(nom,prenom)
return 0
SqlFunc.py
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="agenda"
)
mycursor = mydb.cursor()
def insert(nom,prenom):
var=0
sql = "INSERT INTO contact (numero, nom) VALUES (%s, %s)"
val = (nom, prenom)
if mycursor.execute(sql, val):
mydb.commit()
return "Enregistrement effectué"
else:
return "Echec de l'enregistrement contact déjà enregistré!"
def select():
mycursor.execute("SELECT * FROM contact")
data_from = mycursor.fetchall()
if data_from == "":
return "Aucun contact enregistré"
else:
return data_from
def search(name):
mycursor.execute("SELECT contact.numero, contact.nom WHERE
contact.nom LIKE '%{}%' ORDER BY contact.nom".format(name))
myresult = mycursor.fetchall()
return myresult
def update(old_address,new_address):
sql_request = "UPDATE customers SET address = %s WHERE address = %s"
valors = (old_address, new_address)
if mycursor.execute( sql_request, valors):
mydb.commit()
return "Modification effectuer avec succes"
else:
return "Echec de la modification"
def delete(address):
sql_request = "DELETE FROM customers WHERE address = %s"
func_address = (address)
if mycursor.execute(sql_request,func_address):
mydb.commit()
return "Suppression effectuée"
else:
return "Echec de la suppression"
databases.py
import SqlFunc
class DataBase():
def __int__(self):
self.data_from_databases
@staticmethod
def take_from_mysql():
data_to_model = SqlFunc.select()
return data_to_model
@staticmethod
def search_by_name(contact_name):
search_result = SqlFunc.search(contact_name)
return search_result
@staticmethod
def update_valor(old,new):
update_result = SqlFunc.update(old,new)
return update_result
@staticmethod
def delete_valor(address):
delete_result = SqlFunc.delete(address)
return delete_result
Star_app.py
import sys, Modele,databases
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
from os import system
try:
system('start
C:\Users\yyy\PycharmProjects\TEST_CEI_GUI\mysql\bin\mysqld.exe')
except:
quit()
else:
from Main import MainApp
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
engine.load('C:\UsersyyyPycharmProjectsTEST_CEI_GUIGO7\
main.qml')
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
ctx.setContextProperty("myModel", model)
win.show()
sys.exit(app.exec())
Modele.py
class NewModel(QAbstractListModel):
numero_role = Qt.UserRole + 1
nom_role = Qt.UserRole + 2
_roles = {numero_role: b"numero", nom_role: b"nom"}
def __init__(self):
super(NewModel, self).__init__()
self._contact =
self._data = databases.DataBase().take_from_mysql()
def update(self,search_term):
self.beginResetModel()
self._contact = self._data.search_by_name(search_term)
self.endResetModel()
@pyqtSlot(str)
def search_input(self,searh_input):
if len(searh_input) > 3:
print(searh_input)
self.update(searh_input)
def rowCount(self, parent=None, *args, **kwargs):
return len(self._data)
def data(self, QModelIndex, role=None):
row = QModelIndex.row()
if role == self.numero_role:
return self._data[row]["numero"]
if role == self.nom_role:
return self._data[row]["nom"]
def roleNames(self):
return self._roles
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
Page {
width: 600
height: 400
clip: true
contentHeight: 20
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom//
}
}
}
}
my GUI crashes after execution, and when I modify code nothing is displayed with my view
python python-3.x pyqt qml pyqt5
python python-3.x pyqt qml pyqt5
edited Jan 19 at 19:47
eyllanesc
77.4k103156
77.4k103156
asked Jan 19 at 16:09
Nathan EmonNathan Emon
83
83
You could show the fields in your table contact
– eyllanesc
Jan 19 at 20:38
movectx.setContextProperty("py_MainApp", py_mainapp) ctx.setContextProperty("myModel", model)
beforeengine.load(...)
– eyllanesc
Jan 19 at 22:14
add a comment |
You could show the fields in your table contact
– eyllanesc
Jan 19 at 20:38
movectx.setContextProperty("py_MainApp", py_mainapp) ctx.setContextProperty("myModel", model)
beforeengine.load(...)
– eyllanesc
Jan 19 at 22:14
You could show the fields in your table contact
– eyllanesc
Jan 19 at 20:38
You could show the fields in your table contact
– eyllanesc
Jan 19 at 20:38
move
ctx.setContextProperty("py_MainApp", py_mainapp) ctx.setContextProperty("myModel", model)
before engine.load(...)
– eyllanesc
Jan 19 at 22:14
move
ctx.setContextProperty("py_MainApp", py_mainapp) ctx.setContextProperty("myModel", model)
before engine.load(...)
– eyllanesc
Jan 19 at 22:14
add a comment |
1 Answer
1
active
oldest
votes
The problem is that you are assuming that fetchall()
returns a list of tuples, instead you are assuming that it returns a list of dictionaries so in that case you should change to:
mycursor = mydb.cursor(dictionary=True)
On the other hand if you are going to use the model in QML you must load it as contextProperty before loading the QML:
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
ctx.setContextProperty("myModel", model)
engine.load(r'main.qml')
if not engine.rootObjects():
sys.exit(-1)
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
sys.exit(app.exec())
On the other hand QQmlApplicationEngine waits for a Window or an ApplicationWindow, not a Page, so change the QML to:
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
Another way is using QtSql with QSqlQueryModel:
main.py
from PyQt5 import QtCore, QtGui, QtSql, QtQml
class SqlQueryModel(QtSql.QSqlQueryModel):
def data(self, index, role=QtCore.Qt.DisplayRole):
value = QtCore.QVariant()
if index.isValid():
if role < QtCore.Qt.UserRole:
value = super(SqlQueryModel, self).data(index, role)
else:
columnIdx = role - QtCore.Qt.UserRole - 1;
modelIndex = self.index(index.row(), columnIdx)
value =super(SqlQueryModel, self).data(modelIndex, QtCore.Qt.DisplayRole)
return value
def roleNames(self):
roles = dict()
for i in range(self.record().count()):
roles[QtCore.Qt.UserRole + i +1] = self.record().fieldName(i).encode()
return roles
class Manager(QtCore.QObject):
def __init__(self, parent=None):
super(Manager, self).__init__(parent)
self._model = SqlQueryModel(self)
self.take_from_mysql()
@QtCore.pyqtProperty(SqlQueryModel)
def model(self):
return self._model
@QtCore.pyqtSlot()
def take_from_mysql(self):
self._model.setQuery("SELECT * FROM contact")
@QtCore.pyqtSlot(str)
def search_by_name(self, name):
query = QtSql.QSqlQuery()
query.prepare('''SELECT * FROM contact WHERE nom LIKE ? ORDER BY nom;''')
query.addBindValue("%{}%".format(name))
query.exec()
self._model.setQuery(query)
def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName("localhost")
db.setDatabaseName("agenda")
db.setUserName("root")
db.setPassword("")
if not db.open():
print('''Unable to establish a database connection.n
This example needs SQLite support. Please read
the Qt SQL driver documentation for information
how to build it.nn Click Cancel to exit.''')
return False
return True
if __name__ == '__main__':
import sys
sys.argv += ['--style', 'material']
app = QtGui.QGuiApplication(sys.argv)
if not createConnection():
sys.exit(-1)
manager = Manager()
engine = QtQml.QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("manager", manager)
engine.load("main.qml")
sys.exit(app.exec_())
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: manager.model // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54268942%2fhow-to-see-my-data-in-model-view-qml-with-pyqt5%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The problem is that you are assuming that fetchall()
returns a list of tuples, instead you are assuming that it returns a list of dictionaries so in that case you should change to:
mycursor = mydb.cursor(dictionary=True)
On the other hand if you are going to use the model in QML you must load it as contextProperty before loading the QML:
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
ctx.setContextProperty("myModel", model)
engine.load(r'main.qml')
if not engine.rootObjects():
sys.exit(-1)
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
sys.exit(app.exec())
On the other hand QQmlApplicationEngine waits for a Window or an ApplicationWindow, not a Page, so change the QML to:
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
Another way is using QtSql with QSqlQueryModel:
main.py
from PyQt5 import QtCore, QtGui, QtSql, QtQml
class SqlQueryModel(QtSql.QSqlQueryModel):
def data(self, index, role=QtCore.Qt.DisplayRole):
value = QtCore.QVariant()
if index.isValid():
if role < QtCore.Qt.UserRole:
value = super(SqlQueryModel, self).data(index, role)
else:
columnIdx = role - QtCore.Qt.UserRole - 1;
modelIndex = self.index(index.row(), columnIdx)
value =super(SqlQueryModel, self).data(modelIndex, QtCore.Qt.DisplayRole)
return value
def roleNames(self):
roles = dict()
for i in range(self.record().count()):
roles[QtCore.Qt.UserRole + i +1] = self.record().fieldName(i).encode()
return roles
class Manager(QtCore.QObject):
def __init__(self, parent=None):
super(Manager, self).__init__(parent)
self._model = SqlQueryModel(self)
self.take_from_mysql()
@QtCore.pyqtProperty(SqlQueryModel)
def model(self):
return self._model
@QtCore.pyqtSlot()
def take_from_mysql(self):
self._model.setQuery("SELECT * FROM contact")
@QtCore.pyqtSlot(str)
def search_by_name(self, name):
query = QtSql.QSqlQuery()
query.prepare('''SELECT * FROM contact WHERE nom LIKE ? ORDER BY nom;''')
query.addBindValue("%{}%".format(name))
query.exec()
self._model.setQuery(query)
def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName("localhost")
db.setDatabaseName("agenda")
db.setUserName("root")
db.setPassword("")
if not db.open():
print('''Unable to establish a database connection.n
This example needs SQLite support. Please read
the Qt SQL driver documentation for information
how to build it.nn Click Cancel to exit.''')
return False
return True
if __name__ == '__main__':
import sys
sys.argv += ['--style', 'material']
app = QtGui.QGuiApplication(sys.argv)
if not createConnection():
sys.exit(-1)
manager = Manager()
engine = QtQml.QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("manager", manager)
engine.load("main.qml")
sys.exit(app.exec_())
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: manager.model // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
add a comment |
The problem is that you are assuming that fetchall()
returns a list of tuples, instead you are assuming that it returns a list of dictionaries so in that case you should change to:
mycursor = mydb.cursor(dictionary=True)
On the other hand if you are going to use the model in QML you must load it as contextProperty before loading the QML:
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
ctx.setContextProperty("myModel", model)
engine.load(r'main.qml')
if not engine.rootObjects():
sys.exit(-1)
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
sys.exit(app.exec())
On the other hand QQmlApplicationEngine waits for a Window or an ApplicationWindow, not a Page, so change the QML to:
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
Another way is using QtSql with QSqlQueryModel:
main.py
from PyQt5 import QtCore, QtGui, QtSql, QtQml
class SqlQueryModel(QtSql.QSqlQueryModel):
def data(self, index, role=QtCore.Qt.DisplayRole):
value = QtCore.QVariant()
if index.isValid():
if role < QtCore.Qt.UserRole:
value = super(SqlQueryModel, self).data(index, role)
else:
columnIdx = role - QtCore.Qt.UserRole - 1;
modelIndex = self.index(index.row(), columnIdx)
value =super(SqlQueryModel, self).data(modelIndex, QtCore.Qt.DisplayRole)
return value
def roleNames(self):
roles = dict()
for i in range(self.record().count()):
roles[QtCore.Qt.UserRole + i +1] = self.record().fieldName(i).encode()
return roles
class Manager(QtCore.QObject):
def __init__(self, parent=None):
super(Manager, self).__init__(parent)
self._model = SqlQueryModel(self)
self.take_from_mysql()
@QtCore.pyqtProperty(SqlQueryModel)
def model(self):
return self._model
@QtCore.pyqtSlot()
def take_from_mysql(self):
self._model.setQuery("SELECT * FROM contact")
@QtCore.pyqtSlot(str)
def search_by_name(self, name):
query = QtSql.QSqlQuery()
query.prepare('''SELECT * FROM contact WHERE nom LIKE ? ORDER BY nom;''')
query.addBindValue("%{}%".format(name))
query.exec()
self._model.setQuery(query)
def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName("localhost")
db.setDatabaseName("agenda")
db.setUserName("root")
db.setPassword("")
if not db.open():
print('''Unable to establish a database connection.n
This example needs SQLite support. Please read
the Qt SQL driver documentation for information
how to build it.nn Click Cancel to exit.''')
return False
return True
if __name__ == '__main__':
import sys
sys.argv += ['--style', 'material']
app = QtGui.QGuiApplication(sys.argv)
if not createConnection():
sys.exit(-1)
manager = Manager()
engine = QtQml.QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("manager", manager)
engine.load("main.qml")
sys.exit(app.exec_())
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: manager.model // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
add a comment |
The problem is that you are assuming that fetchall()
returns a list of tuples, instead you are assuming that it returns a list of dictionaries so in that case you should change to:
mycursor = mydb.cursor(dictionary=True)
On the other hand if you are going to use the model in QML you must load it as contextProperty before loading the QML:
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
ctx.setContextProperty("myModel", model)
engine.load(r'main.qml')
if not engine.rootObjects():
sys.exit(-1)
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
sys.exit(app.exec())
On the other hand QQmlApplicationEngine waits for a Window or an ApplicationWindow, not a Page, so change the QML to:
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
Another way is using QtSql with QSqlQueryModel:
main.py
from PyQt5 import QtCore, QtGui, QtSql, QtQml
class SqlQueryModel(QtSql.QSqlQueryModel):
def data(self, index, role=QtCore.Qt.DisplayRole):
value = QtCore.QVariant()
if index.isValid():
if role < QtCore.Qt.UserRole:
value = super(SqlQueryModel, self).data(index, role)
else:
columnIdx = role - QtCore.Qt.UserRole - 1;
modelIndex = self.index(index.row(), columnIdx)
value =super(SqlQueryModel, self).data(modelIndex, QtCore.Qt.DisplayRole)
return value
def roleNames(self):
roles = dict()
for i in range(self.record().count()):
roles[QtCore.Qt.UserRole + i +1] = self.record().fieldName(i).encode()
return roles
class Manager(QtCore.QObject):
def __init__(self, parent=None):
super(Manager, self).__init__(parent)
self._model = SqlQueryModel(self)
self.take_from_mysql()
@QtCore.pyqtProperty(SqlQueryModel)
def model(self):
return self._model
@QtCore.pyqtSlot()
def take_from_mysql(self):
self._model.setQuery("SELECT * FROM contact")
@QtCore.pyqtSlot(str)
def search_by_name(self, name):
query = QtSql.QSqlQuery()
query.prepare('''SELECT * FROM contact WHERE nom LIKE ? ORDER BY nom;''')
query.addBindValue("%{}%".format(name))
query.exec()
self._model.setQuery(query)
def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName("localhost")
db.setDatabaseName("agenda")
db.setUserName("root")
db.setPassword("")
if not db.open():
print('''Unable to establish a database connection.n
This example needs SQLite support. Please read
the Qt SQL driver documentation for information
how to build it.nn Click Cancel to exit.''')
return False
return True
if __name__ == '__main__':
import sys
sys.argv += ['--style', 'material']
app = QtGui.QGuiApplication(sys.argv)
if not createConnection():
sys.exit(-1)
manager = Manager()
engine = QtQml.QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("manager", manager)
engine.load("main.qml")
sys.exit(app.exec_())
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: manager.model // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
The problem is that you are assuming that fetchall()
returns a list of tuples, instead you are assuming that it returns a list of dictionaries so in that case you should change to:
mycursor = mydb.cursor(dictionary=True)
On the other hand if you are going to use the model in QML you must load it as contextProperty before loading the QML:
if __name__ == "__main__":
#data = databases.DataBase.take_from_mysql()
sys.argv += ['--style', 'material']
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
model = Modele.NewModel()
ctx = engine.rootContext()
ctx.setContextProperty("myModel", model)
engine.load(r'main.qml')
if not engine.rootObjects():
sys.exit(-1)
win = engine.rootObjects()[0]
py_mainapp = MainApp(ctx, win)
ctx.setContextProperty("py_MainApp", py_mainapp)
sys.exit(app.exec())
On the other hand QQmlApplicationEngine waits for a Window or an ApplicationWindow, not a Page, so change the QML to:
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: myModel // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
Another way is using QtSql with QSqlQueryModel:
main.py
from PyQt5 import QtCore, QtGui, QtSql, QtQml
class SqlQueryModel(QtSql.QSqlQueryModel):
def data(self, index, role=QtCore.Qt.DisplayRole):
value = QtCore.QVariant()
if index.isValid():
if role < QtCore.Qt.UserRole:
value = super(SqlQueryModel, self).data(index, role)
else:
columnIdx = role - QtCore.Qt.UserRole - 1;
modelIndex = self.index(index.row(), columnIdx)
value =super(SqlQueryModel, self).data(modelIndex, QtCore.Qt.DisplayRole)
return value
def roleNames(self):
roles = dict()
for i in range(self.record().count()):
roles[QtCore.Qt.UserRole + i +1] = self.record().fieldName(i).encode()
return roles
class Manager(QtCore.QObject):
def __init__(self, parent=None):
super(Manager, self).__init__(parent)
self._model = SqlQueryModel(self)
self.take_from_mysql()
@QtCore.pyqtProperty(SqlQueryModel)
def model(self):
return self._model
@QtCore.pyqtSlot()
def take_from_mysql(self):
self._model.setQuery("SELECT * FROM contact")
@QtCore.pyqtSlot(str)
def search_by_name(self, name):
query = QtSql.QSqlQuery()
query.prepare('''SELECT * FROM contact WHERE nom LIKE ? ORDER BY nom;''')
query.addBindValue("%{}%".format(name))
query.exec()
self._model.setQuery(query)
def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName("localhost")
db.setDatabaseName("agenda")
db.setUserName("root")
db.setPassword("")
if not db.open():
print('''Unable to establish a database connection.n
This example needs SQLite support. Please read
the Qt SQL driver documentation for information
how to build it.nn Click Cancel to exit.''')
return False
return True
if __name__ == '__main__':
import sys
sys.argv += ['--style', 'material']
app = QtGui.QGuiApplication(sys.argv)
if not createConnection():
sys.exit(-1)
manager = Manager()
engine = QtQml.QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("manager", manager)
engine.load("main.qml")
sys.exit(app.exec_())
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.4
ApplicationWindow {
width: 600
visible: true
height: 400
title: qsTr("Consulter (Consulter les personnes enregistrer)")
GridView {
id: gridView
anchors.fill: parent
keyNavigationWraps: true
cellWidth: 220
cellHeight: 320
visible: true
model: manager.model // QML connection to python model
delegate: Rectangle {
id: thumb_frame
height: 330
width: 200
Row{
Text{
id: contactnumero
text: numero //
}
Text{
id: contactnom
text: nom
}
}
}
}
}
edited Jan 20 at 1:16
answered Jan 19 at 23:43
eyllanesceyllanesc
77.4k103156
77.4k103156
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54268942%2fhow-to-see-my-data-in-model-view-qml-with-pyqt5%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You could show the fields in your table contact
– eyllanesc
Jan 19 at 20:38
move
ctx.setContextProperty("py_MainApp", py_mainapp) ctx.setContextProperty("myModel", model)
beforeengine.load(...)
– eyllanesc
Jan 19 at 22:14