How to trigger a method when any row is selected in PyQt6 QTableView - qtableview

I need a signal or event from the QtableView to capture the row number user selects
Here I tried an event filter to get the Mouse Button Press event, but nothing got filtered out, yet the same filter works for Context Menu event, Is there any related method to capture signal from table view? (like cellClicked.connect in QTableWidget)
from PyQt6 import QtCore, QtGui, Qt6
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QDialog, QApplication, QWidget, QMainWindow, QHeaderView, QTableView
from PyQt6 import uic
import sys
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self.data = data
def data(self, index, role):
if role == Qt.ItemDataRole.DisplayRole:
return self.data[index.row()][index.column()]
def rowCount(self, index):
return len(self.data)
def columnCount(self, index):
return len(self.data[0])
class UI(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('model.ui', self)
self.tableView.installEventFilter(self)
data = [[4, 9, 2], [1, 0, 0], [3, 5, 0], [3, 3, 2], [7, 8, 9]]
self.model = TableModel(data)
self.tableView.setModel(self.model)
def selected_row(self):
indexes = self.tableView.selectedIndexes()
if indexes:
index = indexes[0]
row = index.row()
print(row)
def eventFilter(self, source, event):
if event.type() == event.Type.MouseButtonPress and source == self.tableView:
self.selected_row()
return super().eventFilter(source, event)
def except_hook(cls, exception, traceback):
sys.__excepthook__(cls, exception, traceback)
if __name__=="__main__":
app = QApplication([])
window = UI()
window.show()
sys.excepthook = except_hook
sys.exit(app.exec())

Related

Filter checked checkboxes

By this I tried to make a minimal reproducible example of what I now have.
Using QSortFilterProxyModel() to find text and a custom SortFilterProxyModel to show all the selected checkboxes.
It looks like both proxy's conflicting eachother and giving the wrong row number back. (There is also an option for adding value with a dialog and also this goes to the wrong row with the custom proxy enabled, but works without the custom proxy).
class winConfigurator(QtWidgets.QMainWindow):
def __init__(self, data=None):
super(winConfigurator,self).__init__()
uic.loadUi(os.path.join(os.path.dirname(__file__), 'winConfiguratorView.ui'), self)
self.leSearch.returnPressed.connect(self.searchField)
self.chMatchSelected.toggled.connect(self.showSelected)
def readFile(self, filename):
self.model = TableModel([headers, newRows])
self.proxy_model = QSortFilterProxyModel()
self.proxy_model.setSourceModel(self.model)
"""
Proxy for 'Show Selected'
"""
self.custom_proxy_model = SortFilterProxyModel()
self.custom_proxy_model.setSourceModel(self.proxy_model)
self.tableView.setModel(self.custom_proxy_model)
def searchField(self):
self.proxy_model.setFilterFixedString(self.leSearch.text())
def showSelected(self, state = None):
self.custom_proxy_model.clearFilter()
checkstate_items = self.model.checks.items()
if state == True:
self.custom_proxy_model.setFilterByCheckbox(checkstate_items)
class SortFilterProxyModel(QSortFilterProxyModel):
def __init__(self, *args, **kwargs):
QSortFilterProxyModel.__init__(self, *args, **kwargs)
self.filters = {}
def setFilterByCheckbox(self, checkstates = {}):
self.filters = checkstates
self.invalidateFilter()
def clearFilter(self):
self.filters = {}
self.invalidateFilter()
def filterAcceptsRow(self, source_row, source_parent):
"""
Check if checkbox is checked and show this row
Slow, 7 seconds for 50k rows.
"""
try:
values = []
if self.filters:
for index, is_checked in self.filters:
if is_checked:
row = index.row()
model = self.sourceModel()
if hasattr(model, 'mapToSource'):
index = model.index(source_row, 0, source_parent)
if not index.parent().isValid():
modelIndex = model.mapToSource(index)
source_row = modelIndex.row()
if row == source_row:
values.append(index)
return any(values)
return True
except Exception as e:
# print(e)
return True

MNIST Shard Descriptor: IndexError: list index out of range

I am working on Federated Learning experiments using Intel OpenFL. I want to distribute my dataset (MNIST) using different non-iidness scenarios.
I am following their official documentation: https://openfl.readthedocs.io/en/latest/source/utilities/splitters_data.html
This is my original working code:
"""Mnist Shard Descriptor."""
import logging
import os
from typing import List
import numpy as np
import requests
from openfl.interface.interactive_api.shard_descriptor import ShardDataset
from openfl.interface.interactive_api.shard_descriptor import ShardDescriptor
logger = logging.getLogger(__name__)
class MnistShardDataset(ShardDataset):
"""Mnist Shard dataset class."""
def __init__(self, x, y, data_type, rank=1, worldsize=1):
"""Initialize MNISTDataset."""
self.data_type = data_type
self.rank = rank
self.worldsize = worldsize
self.x = x[self.rank - 1::self.worldsize]
self.y = y[self.rank - 1::self.worldsize]
def __getitem__(self, index: int):
"""Return an item by the index."""
return self.x[index], self.y[index]
def __len__(self):
"""Return the len of the dataset."""
return len(self.x)
class MnistShardDescriptor(ShardDescriptor):
"""Mnist Shard descriptor class."""
def __init__(
self,
rank_worldsize: str = '1, 1',
**kwargs
):
"""Initialize MnistShardDescriptor."""
self.rank, self.worldsize = tuple(int(num) for num in rank_worldsize.split(','))
(x_train, y_train), (x_test, y_test) = self.download_data()
self.data_by_type = {
'train': (x_train, y_train),
'val': (x_test, y_test)
}
def get_shard_dataset_types(self) -> List[str]:
"""Get available shard dataset types."""
return list(self.data_by_type)
def get_dataset(self, dataset_type='train'):
"""Return a shard dataset by type."""
if dataset_type not in self.data_by_type:
raise Exception(f'Wrong dataset type: {dataset_type}')
return MnistShardDataset(
*self.data_by_type[dataset_type],
data_type=dataset_type,
rank=self.rank,
worldsize=self.worldsize
)
#property
def sample_shape(self):
"""Return the sample shape info."""
return ['28', '28', '1']
#property
def target_shape(self):
"""Return the target shape info."""
return ['28', '28', '1']
#property
def dataset_description(self) -> str:
"""Return the dataset description."""
return (f'Mnist dataset, shard number {self.rank}'
f' out of {self.worldsize}')
def download_data(self):
"""Download prepared dataset."""
local_file_path = 'mnist.npz'
mnist_url = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz'
response = requests.get(mnist_url)
with open(local_file_path, 'wb') as f:
f.write(response.content)
with np.load(local_file_path) as f:
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
#x_train = np.reshape(x_train, (-1, 784))
#x_test = np.reshape(x_test, (-1, 784))
os.remove(local_file_path) # remove mnist.npz
print('Mnist data was loaded!')
return (x_train, y_train), (x_test, y_test)
Basically, I changed the MnistShardDescriptor class in both my 2 nodes of the federation in this way:
...
class MnistShardDescriptor(ShardDescriptor):
"""Mnist Shard descriptor class."""
def __init__(
self,
rank_worldsize: str = '1, 1',
**kwargs
):
"""Initialize MnistShardDescriptor."""
self.rank, self.worldsize = tuple(int(num) for num in rank_worldsize.split(','))
(x_train, y_train), (x_test, y_test) = self.download_data()
train_splitter = RandomNumPyDataSplitter()
test_splitter = RandomNumPyDataSplitter()
train_idx = train_splitter.split(y_train, self.worldsize)[self.rank]
test_idx = test_splitter.split(y_test, self.worldsize)[self.rank]
x_train_shard = x_train[train_idx]
x_test_shard = x_test[test_idx]
self.data_by_type = {
'train': (x_train, y_train),
'val': (x_test, y_test)
}
...
I have this error at the line train_idx:IndexError: list index out of range but only in one of the 2 nodes. I do not know why, because the code are exactly the same on both nodes of my federation.
EDIT: I changed the position of the code I have written above, and in particular I wrote in the class MnistShardDataset rather than MnistShardDescriptor:
class MnistShardDataset(ShardDataset):
"""Mnist Shard dataset class."""
def __init__(self, x, y, data_type, rank=1, worldsize=1):
"""Initialize MNISTDataset."""
self.data_type = data_type
self.rank = rank
self.worldsize = worldsize
self.x = x[self.rank - 1::self.worldsize]
self.y = y[self.rank - 1::self.worldsize]
train_splitter = RandomNumPyDataSplitter()
#test_splitter = RandomNumPyDataSplitter()
train_idx = train_splitter.split(self.y, self.worldsize)[self.rank]
#test_idx = test_splitter.split(self.y, self.worldsize)[self.rank]
x_train_shard = self.x[train_idx]
#x_test_shard = self.x[test_idx]
self.x = x_train_shard
With this I am able to create the federation and, in the same node of the director, the clients start training, and the split is truly random because I ran the experiment 2 times, and each time the envoy had a different number of samples. However in the other node (because I am using 2 nodes, one for each envoy) with the envoy (openFL calls envoy the worker on a client) I have the same error of Index out of rangeā€¦
EDIT2: here is an example of data split using openFL: https://github.com/intel/openfl/blob/develop/openfl-tutorials/interactive_api/PyTorch_Kvasir_UNet/envoy/kvasir_shard_descriptor_with_data_splitter.py
However my dataset is different, and I am not succeeding in adapting this solution. Any other example can you suggest to me, about sharding a dataset like MNIST? A tutorial to follow?
Entire error:
File "/home/lmancuso/envoymnist/mnist_shard_descriptor_with_data_splitter.py", line 61, in __init__
train_idx = train_splitter.split(y_train, self.worldsize)[self.rank]
IndexError: list index out of range
EDIT: interesting point: If I change the dimension of my federation, increasing from 2 to 3 the rank_worldsize inside the envoy_config.yaml, training starts (and the dataset is divided in a random way, so it works, because each node has different number of samples). However it works only because I have 2 nodes, but I created a federation of 3 without the 3 node. Indeed the samples are 8064 for one node and 9856 for another node. However considering that I have 60000 training samples in MNIST, all the remaining samples got lost, because they are supposed to be in the last node (which does not exist).
The only solution I found until now is to reduce the rank of each envoy:
train_idx = train_splitter.split(self.y, self.worldsize)[self.rank-1]

Show and hide tab widgets dynamically with pySide

If I create my UI in QT Designer (and import UI to the script), how can I hide and show tabs in my script?
class Tool(QMainWindow, uiTool.Ui_Tool):
def __init__(self):
super(Tool, self).__init__()
# SETUP UI
self.setupUi(self)
# self.tabWidget.removeTab() ???
There is no way to hide/show the tabs in a tab-widget, so you will need to remove and replace them instead.
Below is a demo script that shows how to do this. I have not attempted to keep track of the original indexes in this example - it just shows the basic usage of the methods involved:
import sys
from PyQt5 import QtCore, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(354, 268)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.tabWidget = QtWidgets.QTabWidget(Form)
self.tabWidget.setObjectName("tabWidget")
self.tabRed = QtWidgets.QWidget()
self.tabRed.setObjectName("tabRed")
self.tabWidget.addTab(self.tabRed, "")
self.tabBlue = QtWidgets.QWidget()
self.tabBlue.setObjectName("tabBlue")
self.tabWidget.addTab(self.tabBlue, "")
self.tabGreen = QtWidgets.QWidget()
self.tabGreen.setObjectName("tabGreen")
self.tabWidget.addTab(self.tabGreen, "")
self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 2)
self.buttonRemove = QtWidgets.QPushButton(Form)
self.buttonRemove.setObjectName("buttonRemove")
self.gridLayout.addWidget(self.buttonRemove, 1, 0, 1, 1)
self.buttonRestore = QtWidgets.QPushButton(Form)
self.buttonRestore.setObjectName("buttonRestore")
self.gridLayout.addWidget(self.buttonRestore, 1, 1, 1, 1)
self.retranslateUi(Form)
self.tabWidget.setCurrentIndex(2)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabRed), _translate("Form", "Red"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabBlue), _translate("Form", "Blue"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabGreen), _translate("Form", "Green"))
self.buttonRemove.setText(_translate("Form", "Remove"))
self.buttonRestore.setText(_translate("Form", "Restore"))
class Window(QtWidgets.QWidget, Ui_Form):
def __init__(self):
super(Window, self).__init__()
self.setupUi(self)
self.buttonRemove.clicked.connect(self.handleButtonRemove)
self.buttonRestore.clicked.connect(self.handleButtonRestore)
self.tab_pages = []
for index in range(self.tabWidget.count()):
self.tab_pages.append((
self.tabWidget.widget(index),
self.tabWidget.tabText(index),
))
def handleButtonRemove(self):
index = self.tabWidget.currentIndex()
if index >= 0:
self.tabWidget.removeTab(index)
def handleButtonRestore(self):
for page, title in self.tab_pages:
if self.tabWidget.indexOf(page) < 0:
self.tabWidget.addTab(page, title)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())

deleting a parent widget through a child QPushButton pyqt

It's been a while I'm searching all over the internet for that, but still couldn't get the answer... basically I have a QVBoxLayout which contains several frames - and each frame contains a button which function is to delete its parent frame. The main code was created using QT Designer and pyuic4. I wrote the two additional functions, one works perfectly ("createFrame") but I'm struggling with the "deleteFrame" one. the label inside the frame shows the index of that frame in the vert_layout "array". the problem I noted on my code is that, using it that way, I can only delete the last frame added. So, can someone help me with this issue?
please see my code below:
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
#Custom button that sends out its own instance as the signal
class MyPushButton(QtGui.QPushButton):
mySignal = QtCore.pyqtSignal(QtGui.QWidget)
def mousePressEvent(self, *args, **kwargs):
self.mySignal.emit(self)
class Functions:
def createFrame(self,mainWindow):
#just local frame no need to store it in the class
frame = QtGui.QFrame()
frame.setGeometry(QtCore.QRect(10, 10, 241, 61))
frame.setFrameShape(QtGui.QFrame.StyledPanel)
frame.setFrameShadow(QtGui.QFrame.Raised)
frame.setObjectName(_fromUtf8("frame"))
pushButton_2 = MyPushButton(frame)
pushButton_2.setGeometry(QtCore.QRect(94, 10, 141, 41))
pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
label = QtGui.QLabel(frame)
label.setGeometry(QtCore.QRect(20, 10, 71, 41))
label.setFrameShape(QtGui.QFrame.NoFrame)
label.setAlignment(QtCore.Qt.AlignCenter)
#the vert_layout belongs to class Ui_MainWindow
mainWindow.vert_layout.addWidget(frame)
label.setObjectName(_fromUtf8("label"))
label.setText(str(mainWindow.vert_layout.indexOf(frame)))
pushButton_2.setText(_translate("MainWindow", "delete this frame and all\n its childs", None))
pushButton_2.mySignal.connect(self.deleteFrame)
#my initial idea was to include the mainWindow (instance of
#Ui_MainWindow class in order to use vert_layout - but apparently
#I need to modify the signal as well, right?
def deleteFrame(self,ref,mainWindow):
#finding the index of the FRAME (mybutton's parent)
#that is to be deleted
frame = mainWindow.vert_layout.itemAt(self.vert_layout.indexOf(ref.parent()))
widget = frame.widget()
if widget is not None:
widget.deleteLater()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 284)
self.vert_layout = QtGui.QVBoxLayout()
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(10, 10, 281, 261))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 277, 257))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.scrollAreaWidgetContents.setLayout(self.vert_layout)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(310, 20, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
f = Functions()
self.pushButton.clicked.connect(lambda: f.createFrame())
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "create", None))
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__== '__main__':
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
All you are currently doing is deleting the self.frame widget each time.
So only the last created one gets deleted. And not the one you actually click on.
Modified your code for what you need. Hope it helps you understand.
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
#Custom button that sends out its own instance as the signal
class MyPushButton(QtGui.QPushButton):
mySignal = QtCore.pyqtSignal(QtGui.QWidget)
def mousePressEvent(self, *args, **kwargs):
self.mySignal.emit(self)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 284)
self.vert_layout = QtGui.QVBoxLayout()
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(10, 10, 281, 261))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 277, 257))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.scrollAreaWidgetContents.setLayout(self.vert_layout)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(310, 20, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton.clicked.connect(lambda: self.createFrame())
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "create", None))
def createFrame(self):
#just local frame no need to store it in the class
frame = QtGui.QFrame()
frame.setGeometry(QtCore.QRect(10, 10, 241, 61))
frame.setFrameShape(QtGui.QFrame.StyledPanel)
frame.setFrameShadow(QtGui.QFrame.Raised)
frame.setObjectName(_fromUtf8("frame"))
pushButton_2 = MyPushButton(frame)
pushButton_2.setGeometry(QtCore.QRect(94, 10, 141, 41))
pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
label = QtGui.QLabel(frame)
label.setGeometry(QtCore.QRect(20, 10, 71, 41))
label.setFrameShape(QtGui.QFrame.NoFrame)
label.setAlignment(QtCore.Qt.AlignCenter)
self.vert_layout.addWidget(frame)
label.setObjectName(_fromUtf8("label"))
label.setText(str(self.vert_layout.indexOf(frame)))
pushButton_2.setText(_translate("MainWindow", "delete this frame and all\n its childs", None))
pushButton_2.mySignal.connect(self.deleteFrame)
def deleteFrame(self,ref):
#finding the index of the FRAME (mybutton's parent)
#that is to be deleted
frame = self.vert_layout.itemAt(self.vert_layout.indexOf(ref.parent()))
widget = frame.widget()
if widget is not None:
widget.deleteLater()
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__== '__main__':
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())

pyqt4 QTableView in QMainWindow with csv input and headers

I am working with a QMainWindow and adding a QTableView widget. The table is to be filled with data from a csv file. The csv file first row has the headers, but I cannot find how to write that row into the headers. Even inputting a test header list does not work.
Also I want to reverse sort on the "time" column.
Here is code restricted to mostly the table:
import sys
import csv
from PyQt4 import QtGui
from PyQt4.QtCore import *
from array import *
class UserWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(UserWindow, self).__init__()
self.specModel = QtGui.QStandardItemModel(self)
self.specList = self.createSpecTable()
self.initUI()
def specData(self):
with open('testFile.csv', 'rb') as csvInput:
for row in csv.reader(csvInput):
if row > 0:
items = [QtGui.QStandardItem(field) for field in row]
self.specModel.appendRow(items)
def createSpecTable(self):
self.specTable = QtGui.QTableView()
# This is a test header - different from what is needed
specHdr = ['Test', 'Date', 'Time', 'Type']
self.specData()
specM = specTableModel(self.specModel, specHdr, self)
self.specTable.setModel(specM)
self.specTable.setShowGrid(False)
vHead = self.specTable.verticalHeader()
vHead.setVisible(False)
hHead = self.specTable.horizontalHeader()
hHead.setStretchLastSection(True)
self.specTable.sortByColumn(3, Qt.DescendingOrder)
return self.specTable
def initUI(self):
self.ctr_frame = QtGui.QWidget()
self.scnBtn = QtGui.QPushButton("Sample")
self.refBtn = QtGui.QPushButton("Reference")
self.stpBtn = QtGui.QPushButton("Blah")
# List Window
self.specList.setModel(self.specModel)
# Layout of Widgets
pGrid = QtGui.QGridLayout()
pGrid.setSpacing(5)
pGrid.addWidget(self.scnBtn, 3, 0, 1, 2)
pGrid.addWidget(self.refBtn, 3, 2, 1, 2)
pGrid.addWidget(self.stpBtn, 3, 4, 1, 2)
pGrid.addWidget(self.specList, 10, 0, 20, 6)
self.ctr_frame.setLayout(pGrid)
self.setCentralWidget(self.ctr_frame)
self.statusBar()
self.setGeometry(300, 300, 400, 300)
self.setWindowTitle('Test')
class specTableModel(QAbstractTableModel):
def __init__(self, datain, headerdata, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.arraydata = datain
self.headerdata = headerdata
def rowCount(self, parent):
return len(self.arraydata)
def columnCount(self, parent):
return len(self.arraydata[0])
def data(self, index, role):
if not index.isValid():
return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.arraydata[index.row()][index.column()])
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.headerdata[col]
return None
def main():
app = QtGui.QApplication(sys.argv)
app.setStyle(QtGui.QStyleFactory.create("plastique"))
ex = UserWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
and here is a really short csv file:
Run,Date,Time,Comment
data1,03/03/2014,00:04,Reference
data2,03/03/2014,02:00,Reference
data5,03/03/2014,02:08,Sample
data6,03/03/2014,13:57,Sample
Also the rowCount & columnCount definitions do not work.
Worked out answers to what I posted: Wrote a 'getHeader' function simply to read the first line of the csv file and returned the list. Added the following to the createSpecTable function:
specHdr = self.getHeader()
self.specModel.setHorizontalHeaderLabels(specHdr)
self.specModel.sort(2, Qt.DescendingOrder)
The last statement solved the reverse sort problem. The header line from the csv file was removed from the table by adding a last line to the specData function:
self.specModelremoveRow(0).
Finally the rowCount and columnCount were corrected with:
def rowCount(self, parent):
return self.arraydata.rowCount()
def columnCount(self, parent):
return self.arraydata.columnCount()