Certainly! Below is a complete Python script using PySide6 that implements a GUI data entry editor similar to SPSS and mimics the Excel ribbon UI. The application provides the following features:
- Separate data and variable viewers with splitters.
- Ribbon-style menu mimicking Excel.
- Create a new time series dataset.
- Load and save time series data from/to a CSV file.
- Add and delete columns and rows.
- Manual input and editing of values in the table.
- Handling different data types.
- Ensuring no duplicated column names.
- Proper data management and synchronization.
- Use of standard icons.
Please make sure you have PySide6 installed. You can install it via pip:
pip install PySide6
Here is the complete code:
import sys
import csv
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QTableWidget, QTableWidgetItem,
QVBoxLayout, QHBoxLayout, QSplitter, QAction, QFileDialog, QDialog,
QLabel, QLineEdit, QPushButton, QMessageBox, QComboBox, QToolBar)
from PySide6.QtGui import QIcon
from PySide6.QtCore import Qt, Slot
class VariableDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Variable Properties")
self.layout = QVBoxLayout()
self.name_label = QLabel("Variable Name:")
self.name_edit = QLineEdit()
self.type_label = QLabel("Data Type:")
self.type_combo = QComboBox()
self.type_combo.addItems(["String", "Integer", "Float", "Date", "Boolean"])
self.ok_button = QPushButton("OK")
self.cancel_button = QPushButton("Cancel")
self.layout.addWidget(self.name_label)
self.layout.addWidget(self.name_edit)
self.layout.addWidget(self.type_label)
self.layout.addWidget(self.type_combo)
self.button_layout = QHBoxLayout()
self.button_layout.addWidget(self.ok_button)
self.button_layout.addWidget(self.cancel_button)
self.layout.addLayout(self.button_layout)
self.setLayout(self.layout)
self.ok_button.clicked.connect(self.accept)
self.cancel_button.clicked.connect(self.reject)
def getData(self):
return self.name_edit.text(), self.type_combo.currentText()
class VariableView(QTableWidget):
def __init__(self, parent=None):
super().__init__(0, 2, parent)
self.setHorizontalHeaderLabels(["Variable Name", "Data Type"])
self.verticalHeader().setVisible(False)
self.cellDoubleClicked.connect(self.editVariable)
def addVariable(self, name, data_type):
row = self.rowCount()
self.insertRow(row)
self.setItem(row, 0, QTableWidgetItem(name))
self.setItem(row, 1, QTableWidgetItem(data_type))
def editVariable(self, row, column):
name_item = self.item(row, 0)
type_item = self.item(row, 1)
dialog = VariableDialog(self)
dialog.name_edit.setText(name_item.text())
dialog.type_combo.setCurrentText(type_item.text())
if dialog.exec():
name, data_type = dialog.getData()
if name.strip() == "":
QMessageBox.warning(self, "Invalid Name", "Variable name cannot be empty.")
return
# Check for duplicate names
for i in range(self.rowCount()):
if i != row and self.item(i, 0).text() == name:
QMessageBox.warning(self, "Duplicate Name", "Variable name must be unique.")
return
name_item.setText(name)
type_item.setText(data_type)
self.parent().data_table.updateColumnType(row, data_type)
def deleteVariable(self, row):
self.removeRow(row)
class DataTable(QTableWidget):
def __init__(self, variable_view, parent=None):
super().__init__(0, 0, parent)
self.variable_view = variable_view
def addVariable(self, name, data_type):
col = self.columnCount()
self.insertColumn(col)
self.setHorizontalHeaderItem(col, QTableWidgetItem(name))
self.adjustDataToType(col, data_type)
def deleteVariable(self, col):
self.removeColumn(col)
def addRow(self):
row = self.rowCount()
self.insertRow(row)
def deleteRow(self, row):
self.removeRow(row)
def updateColumnType(self, col, data_type):
self.adjustDataToType(col, data_type)
def adjustDataToType(self, col, data_type):
# Adjust existing data in the column to match the new data type if necessary
for row in range(self.rowCount()):
item = self.item(row, col)
if item is None:
continue
value = item.text()
if data_type == "Integer":
try:
int(value)
except ValueError:
self.setItem(row, col, QTableWidgetItem(""))
elif data_type == "Float":
try:
float(value)
except ValueError:
self.setItem(row, col, QTableWidgetItem(""))
# Implement other data type adjustments as needed
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Data Entry Editor")
# Create the variable and data views
self.variable_view = VariableView()
self.data_table = DataTable(self.variable_view)
# Set parent references
self.variable_view.parent = self
self.data_table.parent = self
# Create splitters
splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(self.variable_view)
splitter.addWidget(self.data_table)
# Main widget and layout
main_widget = QWidget()
main_layout = QVBoxLayout()
main_layout.addWidget(splitter)
main_widget.setLayout(main_layout)
self.setCentralWidget(main_widget)
# Create the ribbon toolbar
self.createRibbon()
def createRibbon(self):
toolbar = QToolBar("Ribbon")
toolbar.setIconSize(Qt.QSize(16, 16))
self.addToolBar(toolbar)
# New Action
new_act = QAction(QIcon.fromTheme("document-new"), "&New", self)
new_act.triggered.connect(self.newFile)
toolbar.addAction(new_act)
# Open Action
open_act = QAction(QIcon.fromTheme("document-open"), "&Open", self)
open_act.triggered.connect(self.openFile)
toolbar.addAction(open_act)
# Save Action
save_act = QAction(QIcon.fromTheme("document-save"), "&Save", self)
save_act.triggered.connect(self.saveFile)
toolbar.addAction(save_act)
toolbar.addSeparator()
# Add Variable Action
add_var_act = QAction(QIcon.fromTheme("list-add"), "Add &Variable", self)
add_var_act.triggered.connect(self.addVariable)
toolbar.addAction(add_var_act)
# Delete Variable Action
del_var_act = QAction(QIcon.fromTheme("list-remove"), "Delete Variable", self)
del_var_act.triggered.connect(self.deleteVariable)
toolbar.addAction(del_var_act)
# Add Row Action
add_row_act = QAction(QIcon.fromTheme("insert-row"), "Add &Row", self)
add_row_act.triggered.connect(self.addRow)
toolbar.addAction(add_row_act)
# Delete Row Action
del_row_act = QAction(QIcon.fromTheme("delete-row"), "Delete Row", self)
del_row_act.triggered.connect(self.deleteRow)
toolbar.addAction(del_row_act)
@Slot()
def newFile(self):
# Clear the variable view and data table
self.variable_view.setRowCount(0)
self.data_table.setColumnCount(0)
self.data_table.setRowCount(0)
@Slot()
def openFile(self):
file_name, _ = QFileDialog.getOpenFileName(self, "Open CSV", "", "CSV Files (*.csv)")
if file_name:
self.loadCSV(file_name)
@Slot()
def saveFile(self):
file_name, _ = QFileDialog.getSaveFileName(self, "Save CSV", "", "CSV Files (*.csv)")
if file_name:
self.saveCSV(file_name)
def loadCSV(self, file_name):
with open(file_name, 'r', newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
headers = next(reader)
types = next(reader)
# Clear current data
self.variable_view.setRowCount(0)
self.data_table.setColumnCount(0)
self.data_table.setRowCount(0)
# Set up variables
for name, data_type in zip(headers, types):
self.variable_view.addVariable(name, data_type)
self.data_table.addVariable(name, data_type)
# Load data rows
for row_data in reader:
row = self.data_table.rowCount()
self.data_table.insertRow(row)
for col, data in enumerate(row_data):
item = QTableWidgetItem(data)
self.data_table.setItem(row, col, item)
def saveCSV(self, file_name):
headers = [self.variable_view.item(row, 0).text() for row in range(self.variable_view.rowCount())]
types = [self.variable_view.item(row, 1).text() for row in range(self.variable_view.rowCount())]
with open(file_name, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
writer.writerow(types)
for row in range(self.data_table.rowCount()):
row_data = []
for col in range(self.data_table.columnCount()):
item = self.data_table.item(row, col)
row_data.append(item.text() if item else '')
writer.writerow(row_data)
@Slot()
def addVariable(self):
dialog = VariableDialog(self)
if dialog.exec():
name, data_type = dialog.getData()
if name.strip() == "":
QMessageBox.warning(self, "Invalid Name", "Variable name cannot be empty.")
return
# Check for duplicate names
for row in range(self.variable_view.rowCount()):
if self.variable_view.item(row, 0).text() == name:
QMessageBox.warning(self, "Duplicate Name", "Variable name must be unique.")
return
self.variable_view.addVariable(name, data_type)
self.data_table.addVariable(name, data_type)
@Slot()
def deleteVariable(self):
selected = self.variable_view.selectedItems()
if selected:
row = self.variable_view.row(selected[0])
col = row # Keep variables in sync
self.variable_view.deleteVariable(row)
self.data_table.deleteVariable(col)
else:
QMessageBox.information(self, "No Selection", "Please select a variable to delete.")
@Slot()
def addRow(self):
self.data_table.addRow()
@Slot()
def deleteRow(self):
selected = self.data_table.selectedItems()
if selected:
row = self.data_table.row(selected[0])
self.data_table.deleteRow(row)
else:
QMessageBox.information(self, "No Selection", "Please select a row to delete.")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Explanation:
- VariableDialog: A dialog for adding/editing variable names and types.
- VariableView: A
QTableWidget showing a list of variables (columns) and their data types.
- DataTable: A
QTableWidget for data entry, synchronized with the VariableView.
- MainWindow: The main application window containing the variable view and data table, along with the ribbon UI.
Key Features Implemented:
- Separated Views with Splitters:
QSplitter is used to separate the variable view and data table.
- Ribbon UI: A
QToolBar is used to mimic a ribbon UI with standard actions and icons.
- Data Management and Synchronization: When variables are added or deleted, both the variable view and data table are updated to keep them synchronized.
- Data Types Handling: Basic data types are handled, and data in cells is adjusted when the data type changes.
- No Duplicated Column Names: Before adding a new variable, the code checks for existing variable names to prevent duplicates.
- Standard Icons: The code uses standard icons from the current icon theme via
QIcon.fromTheme().
Notes:
- Standard Icons: Make sure your system has a theme that supports the standard icons used (
document-new, document-open, etc.). If icons do not appear, you may need to specify paths to icon files or use different icon names.
- Data Types: The handling of data types is basic. You may need to enhance the
adjustDataToType method to handle parsing and validation more robustly.
- Error Handling: Additional error handling can be implemented as needed.
- CSV Format: The CSV loading and saving assumes the first two rows are headers and data types, respectively. Adjust the code if your CSV files have a different format.
To Run the Application:
- Save the script to a file, e.g.,
data_entry_editor.py.
- Ensure you have PySide6 installed (
pip install PySide6).
- Run the script using Python:
python data_entry_editor.py.
Feel free to enhance the code to suit your specific needs!