analitics

Pages

Showing posts with label QTableView. Show all posts
Showing posts with label QTableView. Show all posts

Wednesday, September 4, 2024

Python 3.13.0rc1 : Use faker with build pandas and PyQt6.

In this tutorial I will show you how I build pandas and use faker and PyQt6.
The faker python module is a powerful library designed to generate fake data, which is particularly useful for testing, filling databases, and creating realistic-looking sample data.
I used python version 3.13.0rc1 and I install with pip tool faker and the pandas and PyQt6 is build with pip tool.
pip install faker
Collecting faker
...
Installing collected packages: six, python-dateutil, faker
Successfully installed faker-28.1.0 python-dateutil-2.9.0.post0 six-1.16.0
The pandas installation fail first time then today works, maybe comes with fixes ...
pip install pandas
...
Successfully built pandas
Installing collected packages: pytz, tzdata, pandas
Successfully installed pandas-2.2.2 pytz-2024.1 tzdata-2024.1
Let's try one example to see how this works, I used copilot from microsoft to generate this first source code:
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QTableView
from PyQt6.QtCore import Qt, QAbstractTableModel
import pandas as pd
from faker import Faker

# Generăm date false folosind Faker
fake = Faker()
data = {
    'Name': [fake.name() for _ in range(100)],
    'Address': [fake.address() for _ in range(100)],
    'Email': [fake.email() for _ in range(100)],
    'IP Address': [fake.ipv4() for _ in range(100)]  # Adăugăm adresa IP
}

# Creăm un DataFrame Pandas
df = pd.DataFrame(data)

# Definim un model pentru QTableView
class PandasModel(QAbstractTableModel):
    def __init__(self, df):
        super().__init__()
        self._df = df

    def rowCount(self, parent=None):
        return len(self._df)

    def columnCount(self, parent=None):
        return self._df.shape[1]

    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if index.isValid():
            if role == Qt.ItemDataRole.DisplayRole:
                return str(self._df.iloc[index.row(), index.column()])
        return None

    def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DisplayRole:
            if orientation == Qt.Orientation.Horizontal:
                return self._df.columns[section]
            else:
                return str(section)
        return None

# Aplicatia PyQt6
app = QApplication(sys.argv)
window = QMainWindow()
view = QTableView()

# Setăm modelul pentru QTableView
model = PandasModel(df)
view.setModel(model)

# Configurăm fereastra principală
window.setCentralWidget(view)
window.resize(800, 600)
window.show()

# Rulăm aplicația
sys.exit(app.exec())