deleting a parent widget through a child QPushButton pyqt - widget

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_())

Related

How to trigger a method when any row is selected in PyQt6 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())

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

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_())

Python 3 Accessing variable result from another Class

I have a little problem with a variable update.
I have my variable declared in my first function as such self.TestVar = 0
then if a certain count ==2 self.TestVar = 2
in a second function (in the same class) but called from within another class I want returning self.TestVar. no way.
AttributeError: 'ThndClass' object has no attribute 'TestVar'
I am most certainly not doing the good way, all I want is accessing self.TestVar = 2 from my other class that's it's but I can't find a proper way to do so in Python.
It looks like my issue is that I get my self.TestVar = 2 in a "if" statement which make it live in another scope (or I might be wrong).
import sys
from PIL import Image
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.TestVar = 0
self.TheCount = 2
if self.TheCount ==2:
self.TestVar = 2
ThndClass()
def Getit(self):
print("called correctly")
print(self.TestVar)
return self.TestVar
def main():
app = QtGui.QApplication([])
mw = MainWindow()
sys.exit(app.exec_())
class ThndClass(QtGui.QWidget):
def __init__(self):
super(ThndClass, self).__init__()
self.initUI2()
def initUI2(self):
print("Class Called")
print(MainWindow.Getit(self))
if __name__ == '__main__':
main()
If I remove the 2nd Class call :
import sys
from PIL import Image
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.TestVar = 0
self.TheCount = 2
if self.TheCount ==2:
self.TestVar = 2
self.Getit()
def Getit(self):
print("called correctly")
print(self.TestVar)
return self.TestVar
def main():
app = QtGui.QApplication([])
mw = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This works correctly, but I want to be able to call def Getit() from another class and get my result. Or simply get a way to directly access self.TestVar from my other class.
When you call
MainWindow.Getit(self)
in ThndClass.initUI2, you are treating MainWindow and ThndClass interchangeably, when they do not have the same attributes. Here is an actual minimal example:
class Parent():
def __init__(self):
pass
class Child1(Parent):
def __init__(self):
super().__init__()
self.foo = "foo"
def method(self):
print(type(self))
print(self.foo)
class Child2(Parent):
def __init__(self):
super().__init__()
self.bar = "bar"
c1 = Child1()
Child1.method(c1) # pass Child1 instance to Child1 instance method
c2 = Child2()
Child1.method(c2) # pass Child2 instance to Child1 instance method
and full output:
<class '__main__.Child1'> # gets a Child1 instance
foo # first call succeeds
<class '__main__.Child2'> # gets a Child2 instance (which doesn't have 'foo')
Traceback (most recent call last):
File "C:/Python34/so.py", line 25, in <module>
Child1.method(c2)
File "C:/Python34/so.py", line 11, in method
print(self.foo)
AttributeError: 'Child2' object has no attribute 'foo' # second call fails
However, as it is not clear what exactly the code is supposed to be doing, I can't suggest a fix. I don't know why you create but don't assign a ThndClass instance in MainWindow.initUI, for example.
Here is one possible fix; pass a Child1 instance to Child2.__init__, then use it either as an argument to Child2.method:
class Child2(Parent):
def __init__(self, c1): # provide Child1 instance as parameter
super().__init__()
self.bar = "bar"
self.method(c1) # pass instance to Child2.method
def method(self, c1):
c1.method() # call Child1.method with c1 as self parameter
(Note that c1.method() is equivalent to Child1.method(c1).)
or make it an instance attribute:
class Child2(Parent):
def __init__(self, c1): # provide Child1 instance as parameter
super().__init__()
self.bar = "bar"
self.c1 = c1 # make Child1 instance a Child2 instance attribute
self.method() # now no argument needed
def method(self):
self.c1.method() # call Child1.method with c1 as self parameter
(Note that self.c1.method() is equivalent to Child1.method(self.c1).)
In use (either way):
>>> c1 = Child1()
>>> c2 = Child2(c1)
<class '__main__.Child1'> # Child1.method gets a Child1 instance
foo # and is called successfully
Thank's to your help jonrsharpe here's my working code :)
import sys
from PIL import Image
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.TestVar = 0
self.TheCount = 2
if self.TheCount ==2:
self.TestVar = 2
Themain = self
ThndClass(Themain)
def Getit(self):
print("called correctly")
print(self.TestVar)
return self.TestVar
def main():
app = QtGui.QApplication([])
mw = MainWindow()
sys.exit(app.exec_())
class ThndClass(QtGui.QWidget):
def __init__(self, Themain):
super(ThndClass, self).__init__()
self.Themain = Themain
self.initUI2()
def initUI2(self):
print("Class Called")
print(self.Themain.Getit())
if __name__ == '__main__':
main()
All working good now : ) Thanks you very much !

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