Displaying pandas dataframe in QMLHow to display a Pandas data frame with PyQt5Add one row to pandas DataFrameSelecting multiple columns in a pandas dataframeRenaming columns in pandasAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column name“Large data” work flows using pandasHow to iterate over rows in a DataFrame in Pandas?Pandas writing dataframe to CSV fileSelect rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers

What's the 2-minute timer on mobile Deutsche Bahn tickets?

What does にとり mean?

Game artist computer workstation set-up – is this overkill?

Counting the Number of Real Roots of A Polynomial

How can I get people to remember my character's gender?

How to pass hash as password to ssh server

Speed up this NIntegrate

How to pass query parameters in URL in Salesforce Summer 19 Release?

Is 'contemporary' ambiguous and if so is there a better word?

Page count conversion from single to double-space for submissions

Will a God Eternal enchanted with Deep Freeze shuffle back into the deck if it dies?

What is the closest airport to the center of the city it serves?

How to remap repeating commands i.e. <number><command>?

Madam I m Adam..please don’t get mad..you will no longer be prime

Why would a military not separate its forces into different branches?

How can Internet speed be 10 times slower without a router than when using the same connection with a router?

Some Russian letters overlap the next line of text when used in drop caps

Why did the Apollo 13 crew extend the LM landing gear?

Enabling a minor mode in all but some buffers

Connecting sentences with dictionary form verbs?

What is a common way to tell if an academic is "above average," or outstanding in their field? Is their h-index (Hirsh index) one of them?

Endgame puzzle: How to avoid stalemate and win?

Is there a proof that the set of real numbers can exactly represent distances?

In Futurama, how many beings has Leela slept with?



Displaying pandas dataframe in QML


How to display a Pandas data frame with PyQt5Add one row to pandas DataFrameSelecting multiple columns in a pandas dataframeRenaming columns in pandasAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column name“Large data” work flows using pandasHow to iterate over rows in a DataFrame in Pandas?Pandas writing dataframe to CSV fileSelect rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have 2 pandas dataframes, one with 6 rows and 7 columns and another one with 21 rows and 12 columns, i would like to display them using QML, while googling i got to know about TableView TableView QML Type. In that example, the data has been entered already in ListElement and it is being shown. But in my case the data is from python pandas dataframe, how can i fetch the columns and rows from pandas straight into QML, should i create those columns well before under listelement? Any help would be appreciated



Note: I have used QtWidgets to display dataframe, it was just a drag and drop tableview and use the model created and set them using tableView.setModel(model). But i am kind of clueless here in QML










share|improve this question
























  • i am using pyqt5

    – Techiesoft
    Mar 23 at 2:47

















1















I have 2 pandas dataframes, one with 6 rows and 7 columns and another one with 21 rows and 12 columns, i would like to display them using QML, while googling i got to know about TableView TableView QML Type. In that example, the data has been entered already in ListElement and it is being shown. But in my case the data is from python pandas dataframe, how can i fetch the columns and rows from pandas straight into QML, should i create those columns well before under listelement? Any help would be appreciated



Note: I have used QtWidgets to display dataframe, it was just a drag and drop tableview and use the model created and set them using tableView.setModel(model). But i am kind of clueless here in QML










share|improve this question
























  • i am using pyqt5

    – Techiesoft
    Mar 23 at 2:47













1












1








1








I have 2 pandas dataframes, one with 6 rows and 7 columns and another one with 21 rows and 12 columns, i would like to display them using QML, while googling i got to know about TableView TableView QML Type. In that example, the data has been entered already in ListElement and it is being shown. But in my case the data is from python pandas dataframe, how can i fetch the columns and rows from pandas straight into QML, should i create those columns well before under listelement? Any help would be appreciated



Note: I have used QtWidgets to display dataframe, it was just a drag and drop tableview and use the model created and set them using tableView.setModel(model). But i am kind of clueless here in QML










share|improve this question
















I have 2 pandas dataframes, one with 6 rows and 7 columns and another one with 21 rows and 12 columns, i would like to display them using QML, while googling i got to know about TableView TableView QML Type. In that example, the data has been entered already in ListElement and it is being shown. But in my case the data is from python pandas dataframe, how can i fetch the columns and rows from pandas straight into QML, should i create those columns well before under listelement? Any help would be appreciated



Note: I have used QtWidgets to display dataframe, it was just a drag and drop tableview and use the model created and set them using tableView.setModel(model). But i am kind of clueless here in QML







python pandas pyqt qml pyqt5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 20:01









eyllanesc

91.3k123565




91.3k123565










asked Mar 23 at 2:33









TechiesoftTechiesoft

649




649












  • i am using pyqt5

    – Techiesoft
    Mar 23 at 2:47

















  • i am using pyqt5

    – Techiesoft
    Mar 23 at 2:47
















i am using pyqt5

– Techiesoft
Mar 23 at 2:47





i am using pyqt5

– Techiesoft
Mar 23 at 2:47












1 Answer
1






active

oldest

votes


















1














You can create a class that inherits from QAbstractTableModel as implemented in this old answer and use the QTableView of QtQuick 2.12 that was released in Qt 5.12 since it supports the QAbstractTableModel type model, so you will have to use the latest versions of PyQt5.



main.py



from PyQt5 import QtCore, QtGui, QtQml
import numpy as np
import pandas as pd

class DataFrameModel(QtCore.QAbstractTableModel):
DtypeRole = QtCore.Qt.UserRole + 1000
ValueRole = QtCore.Qt.UserRole + 1001

def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df

def setDataFrame(self, dataframe):
self.beginResetModel()
self._dataframe = dataframe.copy()
self.endResetModel()

def dataFrame(self):
return self._dataframe

dataFrame = QtCore.pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)

@QtCore.pyqtSlot(int, QtCore.Qt.Orientation, result=str)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._dataframe.columns[section]
else:
return str(self._dataframe.index[section])
return QtCore.QVariant()

def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self._dataframe.index)

def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return self._dataframe.columns.size

def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid() or not (0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()):
return QtCore.QVariant()
row = self._dataframe.index[index.row()]
col = self._dataframe.columns[index.column()]
dt = self._dataframe[col].dtype

val = self._dataframe.iloc[row][col]
if role == QtCore.Qt.DisplayRole:
return str(val)
elif role == DataFrameModel.ValueRole:
return val
if role == DataFrameModel.DtypeRole:
return dt
return QtCore.QVariant()

def roleNames(self):
roles =
QtCore.Qt.DisplayRole: b'display',
DataFrameModel.DtypeRole: b'dtype',
DataFrameModel.ValueRole: b'value'

return roles

if __name__ == "__main__":
import os
import sys

app = QtGui.QGuiApplication(sys.argv)
df = pd.DataFrame(np.random.randint(0, 100, size=(6, 7)), columns=list('ABCDEFG'))
print(df)
model = DataFrameModel(df)
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("table_model", model)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())


main.qml



import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Window 2.11

Window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: '#222222'

TableView
id: tableView

columnWidthProvider: function (column) return 100;
rowHeightProvider: function (column) return 60;
anchors.fill: parent
leftMargin: rowsHeader.implicitWidth
topMargin: columnsHeader.implicitHeight
model: table_model
delegate: Rectangle
color: parseFloat(display) > 50 ? 'green' : 'red'
Text
text: display
anchors.fill: parent
anchors.margins: 10
color: 'white'
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter


Rectangle // mask the headers
z: 3
color: "#222222"
y: tableView.contentY
x: tableView.contentX
width: tableView.leftMargin
height: tableView.topMargin


Row
id: columnsHeader
y: tableView.contentY
z: 2
Repeater
model: tableView.columns > 0 ? tableView.columns : 1
Label
width: tableView.columnWidthProvider(modelData)
height: 35
text: table_model.headerData(modelData, Qt.Horizontal)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"



Column
id: rowsHeader
x: tableView.contentX
z: 2
Repeater
model: tableView.rows > 0 ? tableView.rows : 1
Label
width: 40
height: tableView.rowHeightProvider(modelData)
text: table_model.headerData(modelData, Qt.Vertical)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"




ScrollIndicator.horizontal: ScrollIndicator
ScrollIndicator.vertical: ScrollIndicator




enter image description here



I have used:



  • Python 3.7.2

  • PyQt5 5.12.1

  • Qt 5.12.2

  • pandas 0.24.1





share|improve this answer

























  • it works, however i dont get the headers

    – Techiesoft
    Mar 23 at 3:36






  • 1





    @Techiesoft In the TableView of Qt Quick 2.12 they do not come with headers but implementing them is easy with Column, Row and Repeaters as I did in my answer

    – eyllanesc
    Mar 23 at 3:51











  • what is that index on the left..is it coming from pandas dataframe?

    – Techiesoft
    Mar 23 at 4:07











  • if i want to change the cell color based on the numbers , should i write any js function?

    – Techiesoft
    Mar 23 at 4:13











  • Sorted Dataframes not showing up as expected, added the image in the question, can you please check

    – Techiesoft
    Mar 23 at 12:48











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



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310051%2fdisplaying-pandas-dataframe-in-qml%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









1














You can create a class that inherits from QAbstractTableModel as implemented in this old answer and use the QTableView of QtQuick 2.12 that was released in Qt 5.12 since it supports the QAbstractTableModel type model, so you will have to use the latest versions of PyQt5.



main.py



from PyQt5 import QtCore, QtGui, QtQml
import numpy as np
import pandas as pd

class DataFrameModel(QtCore.QAbstractTableModel):
DtypeRole = QtCore.Qt.UserRole + 1000
ValueRole = QtCore.Qt.UserRole + 1001

def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df

def setDataFrame(self, dataframe):
self.beginResetModel()
self._dataframe = dataframe.copy()
self.endResetModel()

def dataFrame(self):
return self._dataframe

dataFrame = QtCore.pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)

@QtCore.pyqtSlot(int, QtCore.Qt.Orientation, result=str)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._dataframe.columns[section]
else:
return str(self._dataframe.index[section])
return QtCore.QVariant()

def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self._dataframe.index)

def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return self._dataframe.columns.size

def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid() or not (0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()):
return QtCore.QVariant()
row = self._dataframe.index[index.row()]
col = self._dataframe.columns[index.column()]
dt = self._dataframe[col].dtype

val = self._dataframe.iloc[row][col]
if role == QtCore.Qt.DisplayRole:
return str(val)
elif role == DataFrameModel.ValueRole:
return val
if role == DataFrameModel.DtypeRole:
return dt
return QtCore.QVariant()

def roleNames(self):
roles =
QtCore.Qt.DisplayRole: b'display',
DataFrameModel.DtypeRole: b'dtype',
DataFrameModel.ValueRole: b'value'

return roles

if __name__ == "__main__":
import os
import sys

app = QtGui.QGuiApplication(sys.argv)
df = pd.DataFrame(np.random.randint(0, 100, size=(6, 7)), columns=list('ABCDEFG'))
print(df)
model = DataFrameModel(df)
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("table_model", model)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())


main.qml



import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Window 2.11

Window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: '#222222'

TableView
id: tableView

columnWidthProvider: function (column) return 100;
rowHeightProvider: function (column) return 60;
anchors.fill: parent
leftMargin: rowsHeader.implicitWidth
topMargin: columnsHeader.implicitHeight
model: table_model
delegate: Rectangle
color: parseFloat(display) > 50 ? 'green' : 'red'
Text
text: display
anchors.fill: parent
anchors.margins: 10
color: 'white'
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter


Rectangle // mask the headers
z: 3
color: "#222222"
y: tableView.contentY
x: tableView.contentX
width: tableView.leftMargin
height: tableView.topMargin


Row
id: columnsHeader
y: tableView.contentY
z: 2
Repeater
model: tableView.columns > 0 ? tableView.columns : 1
Label
width: tableView.columnWidthProvider(modelData)
height: 35
text: table_model.headerData(modelData, Qt.Horizontal)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"



Column
id: rowsHeader
x: tableView.contentX
z: 2
Repeater
model: tableView.rows > 0 ? tableView.rows : 1
Label
width: 40
height: tableView.rowHeightProvider(modelData)
text: table_model.headerData(modelData, Qt.Vertical)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"




ScrollIndicator.horizontal: ScrollIndicator
ScrollIndicator.vertical: ScrollIndicator




enter image description here



I have used:



  • Python 3.7.2

  • PyQt5 5.12.1

  • Qt 5.12.2

  • pandas 0.24.1





share|improve this answer

























  • it works, however i dont get the headers

    – Techiesoft
    Mar 23 at 3:36






  • 1





    @Techiesoft In the TableView of Qt Quick 2.12 they do not come with headers but implementing them is easy with Column, Row and Repeaters as I did in my answer

    – eyllanesc
    Mar 23 at 3:51











  • what is that index on the left..is it coming from pandas dataframe?

    – Techiesoft
    Mar 23 at 4:07











  • if i want to change the cell color based on the numbers , should i write any js function?

    – Techiesoft
    Mar 23 at 4:13











  • Sorted Dataframes not showing up as expected, added the image in the question, can you please check

    – Techiesoft
    Mar 23 at 12:48















1














You can create a class that inherits from QAbstractTableModel as implemented in this old answer and use the QTableView of QtQuick 2.12 that was released in Qt 5.12 since it supports the QAbstractTableModel type model, so you will have to use the latest versions of PyQt5.



main.py



from PyQt5 import QtCore, QtGui, QtQml
import numpy as np
import pandas as pd

class DataFrameModel(QtCore.QAbstractTableModel):
DtypeRole = QtCore.Qt.UserRole + 1000
ValueRole = QtCore.Qt.UserRole + 1001

def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df

def setDataFrame(self, dataframe):
self.beginResetModel()
self._dataframe = dataframe.copy()
self.endResetModel()

def dataFrame(self):
return self._dataframe

dataFrame = QtCore.pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)

@QtCore.pyqtSlot(int, QtCore.Qt.Orientation, result=str)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._dataframe.columns[section]
else:
return str(self._dataframe.index[section])
return QtCore.QVariant()

def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self._dataframe.index)

def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return self._dataframe.columns.size

def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid() or not (0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()):
return QtCore.QVariant()
row = self._dataframe.index[index.row()]
col = self._dataframe.columns[index.column()]
dt = self._dataframe[col].dtype

val = self._dataframe.iloc[row][col]
if role == QtCore.Qt.DisplayRole:
return str(val)
elif role == DataFrameModel.ValueRole:
return val
if role == DataFrameModel.DtypeRole:
return dt
return QtCore.QVariant()

def roleNames(self):
roles =
QtCore.Qt.DisplayRole: b'display',
DataFrameModel.DtypeRole: b'dtype',
DataFrameModel.ValueRole: b'value'

return roles

if __name__ == "__main__":
import os
import sys

app = QtGui.QGuiApplication(sys.argv)
df = pd.DataFrame(np.random.randint(0, 100, size=(6, 7)), columns=list('ABCDEFG'))
print(df)
model = DataFrameModel(df)
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("table_model", model)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())


main.qml



import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Window 2.11

Window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: '#222222'

TableView
id: tableView

columnWidthProvider: function (column) return 100;
rowHeightProvider: function (column) return 60;
anchors.fill: parent
leftMargin: rowsHeader.implicitWidth
topMargin: columnsHeader.implicitHeight
model: table_model
delegate: Rectangle
color: parseFloat(display) > 50 ? 'green' : 'red'
Text
text: display
anchors.fill: parent
anchors.margins: 10
color: 'white'
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter


Rectangle // mask the headers
z: 3
color: "#222222"
y: tableView.contentY
x: tableView.contentX
width: tableView.leftMargin
height: tableView.topMargin


Row
id: columnsHeader
y: tableView.contentY
z: 2
Repeater
model: tableView.columns > 0 ? tableView.columns : 1
Label
width: tableView.columnWidthProvider(modelData)
height: 35
text: table_model.headerData(modelData, Qt.Horizontal)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"



Column
id: rowsHeader
x: tableView.contentX
z: 2
Repeater
model: tableView.rows > 0 ? tableView.rows : 1
Label
width: 40
height: tableView.rowHeightProvider(modelData)
text: table_model.headerData(modelData, Qt.Vertical)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"




ScrollIndicator.horizontal: ScrollIndicator
ScrollIndicator.vertical: ScrollIndicator




enter image description here



I have used:



  • Python 3.7.2

  • PyQt5 5.12.1

  • Qt 5.12.2

  • pandas 0.24.1





share|improve this answer

























  • it works, however i dont get the headers

    – Techiesoft
    Mar 23 at 3:36






  • 1





    @Techiesoft In the TableView of Qt Quick 2.12 they do not come with headers but implementing them is easy with Column, Row and Repeaters as I did in my answer

    – eyllanesc
    Mar 23 at 3:51











  • what is that index on the left..is it coming from pandas dataframe?

    – Techiesoft
    Mar 23 at 4:07











  • if i want to change the cell color based on the numbers , should i write any js function?

    – Techiesoft
    Mar 23 at 4:13











  • Sorted Dataframes not showing up as expected, added the image in the question, can you please check

    – Techiesoft
    Mar 23 at 12:48













1












1








1







You can create a class that inherits from QAbstractTableModel as implemented in this old answer and use the QTableView of QtQuick 2.12 that was released in Qt 5.12 since it supports the QAbstractTableModel type model, so you will have to use the latest versions of PyQt5.



main.py



from PyQt5 import QtCore, QtGui, QtQml
import numpy as np
import pandas as pd

class DataFrameModel(QtCore.QAbstractTableModel):
DtypeRole = QtCore.Qt.UserRole + 1000
ValueRole = QtCore.Qt.UserRole + 1001

def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df

def setDataFrame(self, dataframe):
self.beginResetModel()
self._dataframe = dataframe.copy()
self.endResetModel()

def dataFrame(self):
return self._dataframe

dataFrame = QtCore.pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)

@QtCore.pyqtSlot(int, QtCore.Qt.Orientation, result=str)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._dataframe.columns[section]
else:
return str(self._dataframe.index[section])
return QtCore.QVariant()

def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self._dataframe.index)

def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return self._dataframe.columns.size

def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid() or not (0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()):
return QtCore.QVariant()
row = self._dataframe.index[index.row()]
col = self._dataframe.columns[index.column()]
dt = self._dataframe[col].dtype

val = self._dataframe.iloc[row][col]
if role == QtCore.Qt.DisplayRole:
return str(val)
elif role == DataFrameModel.ValueRole:
return val
if role == DataFrameModel.DtypeRole:
return dt
return QtCore.QVariant()

def roleNames(self):
roles =
QtCore.Qt.DisplayRole: b'display',
DataFrameModel.DtypeRole: b'dtype',
DataFrameModel.ValueRole: b'value'

return roles

if __name__ == "__main__":
import os
import sys

app = QtGui.QGuiApplication(sys.argv)
df = pd.DataFrame(np.random.randint(0, 100, size=(6, 7)), columns=list('ABCDEFG'))
print(df)
model = DataFrameModel(df)
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("table_model", model)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())


main.qml



import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Window 2.11

Window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: '#222222'

TableView
id: tableView

columnWidthProvider: function (column) return 100;
rowHeightProvider: function (column) return 60;
anchors.fill: parent
leftMargin: rowsHeader.implicitWidth
topMargin: columnsHeader.implicitHeight
model: table_model
delegate: Rectangle
color: parseFloat(display) > 50 ? 'green' : 'red'
Text
text: display
anchors.fill: parent
anchors.margins: 10
color: 'white'
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter


Rectangle // mask the headers
z: 3
color: "#222222"
y: tableView.contentY
x: tableView.contentX
width: tableView.leftMargin
height: tableView.topMargin


Row
id: columnsHeader
y: tableView.contentY
z: 2
Repeater
model: tableView.columns > 0 ? tableView.columns : 1
Label
width: tableView.columnWidthProvider(modelData)
height: 35
text: table_model.headerData(modelData, Qt.Horizontal)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"



Column
id: rowsHeader
x: tableView.contentX
z: 2
Repeater
model: tableView.rows > 0 ? tableView.rows : 1
Label
width: 40
height: tableView.rowHeightProvider(modelData)
text: table_model.headerData(modelData, Qt.Vertical)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"




ScrollIndicator.horizontal: ScrollIndicator
ScrollIndicator.vertical: ScrollIndicator




enter image description here



I have used:



  • Python 3.7.2

  • PyQt5 5.12.1

  • Qt 5.12.2

  • pandas 0.24.1





share|improve this answer















You can create a class that inherits from QAbstractTableModel as implemented in this old answer and use the QTableView of QtQuick 2.12 that was released in Qt 5.12 since it supports the QAbstractTableModel type model, so you will have to use the latest versions of PyQt5.



main.py



from PyQt5 import QtCore, QtGui, QtQml
import numpy as np
import pandas as pd

class DataFrameModel(QtCore.QAbstractTableModel):
DtypeRole = QtCore.Qt.UserRole + 1000
ValueRole = QtCore.Qt.UserRole + 1001

def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df

def setDataFrame(self, dataframe):
self.beginResetModel()
self._dataframe = dataframe.copy()
self.endResetModel()

def dataFrame(self):
return self._dataframe

dataFrame = QtCore.pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)

@QtCore.pyqtSlot(int, QtCore.Qt.Orientation, result=str)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._dataframe.columns[section]
else:
return str(self._dataframe.index[section])
return QtCore.QVariant()

def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self._dataframe.index)

def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return self._dataframe.columns.size

def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid() or not (0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()):
return QtCore.QVariant()
row = self._dataframe.index[index.row()]
col = self._dataframe.columns[index.column()]
dt = self._dataframe[col].dtype

val = self._dataframe.iloc[row][col]
if role == QtCore.Qt.DisplayRole:
return str(val)
elif role == DataFrameModel.ValueRole:
return val
if role == DataFrameModel.DtypeRole:
return dt
return QtCore.QVariant()

def roleNames(self):
roles =
QtCore.Qt.DisplayRole: b'display',
DataFrameModel.DtypeRole: b'dtype',
DataFrameModel.ValueRole: b'value'

return roles

if __name__ == "__main__":
import os
import sys

app = QtGui.QGuiApplication(sys.argv)
df = pd.DataFrame(np.random.randint(0, 100, size=(6, 7)), columns=list('ABCDEFG'))
print(df)
model = DataFrameModel(df)
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("table_model", model)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())


main.qml



import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Window 2.11

Window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: '#222222'

TableView
id: tableView

columnWidthProvider: function (column) return 100;
rowHeightProvider: function (column) return 60;
anchors.fill: parent
leftMargin: rowsHeader.implicitWidth
topMargin: columnsHeader.implicitHeight
model: table_model
delegate: Rectangle
color: parseFloat(display) > 50 ? 'green' : 'red'
Text
text: display
anchors.fill: parent
anchors.margins: 10
color: 'white'
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter


Rectangle // mask the headers
z: 3
color: "#222222"
y: tableView.contentY
x: tableView.contentX
width: tableView.leftMargin
height: tableView.topMargin


Row
id: columnsHeader
y: tableView.contentY
z: 2
Repeater
model: tableView.columns > 0 ? tableView.columns : 1
Label
width: tableView.columnWidthProvider(modelData)
height: 35
text: table_model.headerData(modelData, Qt.Horizontal)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"



Column
id: rowsHeader
x: tableView.contentX
z: 2
Repeater
model: tableView.rows > 0 ? tableView.rows : 1
Label
width: 40
height: tableView.rowHeightProvider(modelData)
text: table_model.headerData(modelData, Qt.Vertical)
color: '#aaaaaa'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter

background: Rectangle color: "#333333"




ScrollIndicator.horizontal: ScrollIndicator
ScrollIndicator.vertical: ScrollIndicator




enter image description here



I have used:



  • Python 3.7.2

  • PyQt5 5.12.1

  • Qt 5.12.2

  • pandas 0.24.1






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 23 at 4:35

























answered Mar 23 at 3:08









eyllanesceyllanesc

91.3k123565




91.3k123565












  • it works, however i dont get the headers

    – Techiesoft
    Mar 23 at 3:36






  • 1





    @Techiesoft In the TableView of Qt Quick 2.12 they do not come with headers but implementing them is easy with Column, Row and Repeaters as I did in my answer

    – eyllanesc
    Mar 23 at 3:51











  • what is that index on the left..is it coming from pandas dataframe?

    – Techiesoft
    Mar 23 at 4:07











  • if i want to change the cell color based on the numbers , should i write any js function?

    – Techiesoft
    Mar 23 at 4:13











  • Sorted Dataframes not showing up as expected, added the image in the question, can you please check

    – Techiesoft
    Mar 23 at 12:48

















  • it works, however i dont get the headers

    – Techiesoft
    Mar 23 at 3:36






  • 1





    @Techiesoft In the TableView of Qt Quick 2.12 they do not come with headers but implementing them is easy with Column, Row and Repeaters as I did in my answer

    – eyllanesc
    Mar 23 at 3:51











  • what is that index on the left..is it coming from pandas dataframe?

    – Techiesoft
    Mar 23 at 4:07











  • if i want to change the cell color based on the numbers , should i write any js function?

    – Techiesoft
    Mar 23 at 4:13











  • Sorted Dataframes not showing up as expected, added the image in the question, can you please check

    – Techiesoft
    Mar 23 at 12:48
















it works, however i dont get the headers

– Techiesoft
Mar 23 at 3:36





it works, however i dont get the headers

– Techiesoft
Mar 23 at 3:36




1




1





@Techiesoft In the TableView of Qt Quick 2.12 they do not come with headers but implementing them is easy with Column, Row and Repeaters as I did in my answer

– eyllanesc
Mar 23 at 3:51





@Techiesoft In the TableView of Qt Quick 2.12 they do not come with headers but implementing them is easy with Column, Row and Repeaters as I did in my answer

– eyllanesc
Mar 23 at 3:51













what is that index on the left..is it coming from pandas dataframe?

– Techiesoft
Mar 23 at 4:07





what is that index on the left..is it coming from pandas dataframe?

– Techiesoft
Mar 23 at 4:07













if i want to change the cell color based on the numbers , should i write any js function?

– Techiesoft
Mar 23 at 4:13





if i want to change the cell color based on the numbers , should i write any js function?

– Techiesoft
Mar 23 at 4:13













Sorted Dataframes not showing up as expected, added the image in the question, can you please check

– Techiesoft
Mar 23 at 12:48





Sorted Dataframes not showing up as expected, added the image in the question, can you please check

– Techiesoft
Mar 23 at 12:48



















draft saved

draft discarded
















































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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310051%2fdisplaying-pandas-dataframe-in-qml%23new-answer', 'question_page');

);

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







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현