Using the QTDesigner I made a simple QListWidge that contains three items
Apple
Banana
Orange
My Goal, when one of those options is selected it launches a specific function. For some reason I cannot figure this out and I can't find anything within my Google searches. I am new to pyQT so maybe I'm just using the incorrect terms.
Using QT Designer I can set the SIGNAL and SLOT, but the effect is for every single item within the QListWidget, it is not specific.
Here is the code I am concerned with
QtCore.QObject.connect(self.listWidget, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem*)")), MainWindow.close)
That code is closing the main window when any QListWidgetItem is selected. I want it to only close when "apple" is selected. I want Banana and Orange to do something else.
Seems like all the examples I find online are not addressing if you want item A to do something vs item B. They all just use a generic sample in which all items do the same thing.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGuii
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)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.listWidget = QtGui.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(50, 60, 256, 241))
self.listWidget.setObjectName(_fromUtf8("listWidget"))
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.listWidget, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem*)")), MainWindow.close)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
__sortingEnabled = self.listWidget.isSortingEnabled()
self.listWidget.setSortingEnabled(False)
item = self.listWidget.item(0)
item.setText(_translate("MainWindow", "apple", None))
item = self.listWidget.item(1)
item.setText(_translate("MainWindow", "banana", None))
item = self.listWidget.item(2)
item.setText(_translate("MainWindow", "orange", None))
self.listWidget.setSortingEnabled(__sortingEnabled)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Was able to piece together the solution using the website below and some example scripts floating around. They key to the solution was the .item
.item(0) is reviewing what is currently set at index 0. The website below showed that I could attach a .isSelected() that would return True when a list item is selected.
With both pieces of information I can now take a specific action when a specific item is selected.
http://doc.qt.io/qt-4.8/qlistwidgetitem.html#isSelected
QtCore.QObject.connect(self.listWidget, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem*)")), self.closewindow)
def closewindow(self):
apple = self.listWidget.item(0).isSelected()
banana = self.listWidget.item(1).isSelected()
if apple == True:
self.exitprogram()
elif banana == True:
print 'Banana selected'
def exitprogram(self):
sys.exit()
Related
I'm having a QListView with a QFileSystemModel. Based on a selection in a QTreeView, the QListView shows the content of the folder.
Now I need to change the color of the filenames depending on some condition.
The initial idea would be to iterate over the items in the QListView and set the color for each item depending on whether the condition is fulfilled. However this seems to be impossible, since the setData() method of QFileSystemModel only accepts changes to the EditRole, ignoring something like [see this]
self.FileModel.setData(index, QtGui.QBrush(QtCore.Qt.red), role=QtCore.Qt.ForegroundRole)
This has also been pointed out here
and the suggestion in the latter was to subclass QItemDelegate for the purpose of colorizing items in the QListView.
I therefore subclassed QStyledItemDelegate and reimplemented its paint() method to show the filename in green, if the condition is fulfilled - which works fine. However it now looks kind of ugly: File icons are lost and the "mouse_over" effect is not working anymore.
While this subclassing is anyway a messy work-around, my top-level question would be
Is there a way to colorize items in a QListView connected to a QFileSystemModel based on a condition?
Now provided that this might not be the case and sticking to the subclassing of QItemDelegate,
Is there a way to get the original behaviour with nice selections and icons back?
Does anyone know which ItemDelegate is originally used for QFileSystemModel in a QListView and how to use it?
Is it possible to get its source code and copy the paint method from there ?
Here is a minimal code that uses subclassing and shows the descibed behaviour. It uses a QLineEdit where one can type in a string, such that all files containing that string are highlighted in green.
import sys
from PyQt4 import QtGui, QtCore
class MyFileViewDelegate(QtGui.QStyledItemDelegate ):
def __init__(self, parent=None, *args, **kwargs):
QtGui.QItemDelegate.__init__(self, parent, *args)
self.condition = None
self.isMatch = False
self.brush_active = QtGui.QBrush(QtGui.QColor("#79b9ed"))
self.brush_active_matched = QtGui.QBrush(QtGui.QColor("#58cd1c"))
self.pen = QtGui.QPen(QtGui.QColor("#414141") )
self.pen_matched = QtGui.QPen(QtGui.QColor("#39c819") )
self.pen_active = QtGui.QPen(QtGui.QColor("#eef2fd") )
self.pen_active_matched = QtGui.QPen(QtGui.QColor("#e7fade") )
def paint(self, painter, option, index):
text = index.data(QtCore.Qt.DisplayRole)
self.matchText(text)
painter.save()
######## set background
painter.setPen(QtGui.QPen(QtCore.Qt.NoPen))
if option.state & QtGui.QStyle.State_Selected:
if self.isMatch:
painter.setBrush(self.brush_active_matched)
else:
painter.setBrush(self.brush_active)
painter.drawRect(option.rect)
######## set font color
if option.state & QtGui.QStyle.State_Selected:
if self.isMatch:
painter.setPen(self.pen_active_matched)
else:
painter.setPen(self.pen_active)
else:
if self.isMatch:
painter.setPen(self.pen_matched)
else:
painter.setPen(self.pen)
painter.drawText(option.rect, QtCore.Qt.AlignLeft, text)
painter.restore()
def matchText(self, filename):
# testing condition. In the real case this is much more complicated
if (self.condition != None) and (self.condition != "") and (self.condition in filename):
self.isMatch = True
else:
self.isMatch = False
def setCondition(self, condition):
self.condition = condition
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None, useDelegate = False):
super(MainWidget, self).__init__(parent)
self.setLayout(QtGui.QVBoxLayout())
self.FolderModel = QtGui.QFileSystemModel()
self.FolderModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllDirs)
self.FolderModel.setRootPath("")
self.FolderView = QtGui.QTreeView(parent=self)
self.FolderView.setModel(self.FolderModel)
self.FolderView.setHeaderHidden(True)
self.FolderView.hideColumn(1)
self.FolderView.hideColumn(2)
self.FolderView.hideColumn(3)
self.FolderView.expanded.connect(self.FolderView.scrollTo)
self.FolderView.clicked[QtCore.QModelIndex].connect(self.browserClicked)
self.FileModel = QtGui.QFileSystemModel()
self.FileModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
self.FileView = QtGui.QListView(parent=self)
self.FileView.setModel(self.FileModel)
self.FileViewDelegate = None
if useDelegate:
self.FileViewDelegate = MyFileViewDelegate()
self.FileView.setItemDelegate(self.FileViewDelegate)
self.FileView.setSelectionMode( QtGui.QAbstractItemView.ExtendedSelection )
self.LineEdit = QtGui.QLineEdit()
self.LineEdit.textChanged.connect(self.changeCondition)
# Add Widgets to layout
self.layout().addWidget(self.FolderView)
self.layout().addWidget(self.FileView)
self.layout().addWidget(self.LineEdit)
def changeCondition(self, text):
if self.FileViewDelegate:
self.FileViewDelegate.setCondition(text)
def browserClicked(self, index):
# the signal passes the index of the clicked item
# set the FileView's root_index to the clicked index
dir_path = self.FileModel.filePath(index)
root_index = self.FileModel.setRootPath(dir_path)
self.FileView.setRootIndex(root_index)
class App(QtGui.QMainWindow):
def __init__(self, parent=None, useDelegate=False):
super(App, self).__init__(parent)
self.central = MainWidget(parent =self, useDelegate=useDelegate)
self.setCentralWidget(self.central)
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
thisapp = App(None, True) # set False to view App without custom FileViewDelegate
thisapp.show()
sys.exit(app.exec_())
This is the comparison of how it looks with and without subclassing QItemDelegate:
just to mention, another problem with this code is, that once the condition is changed, one needs to move the mouse into the QFileView to initiate the repainting. I wonder which slot I could use to connect to the LineEdit.textChange signal to do that directly.
There's no need for an item-delegate. It can be achieved much more simply by reimplementing the data method of the QFileSystemModel:
class FileSystemModel(QtGui.QFileSystemModel):
def __init__(self, *args, **kwargs):
super(FileSystemModel, self).__init__(*args, **kwargs)
self.condition = None
def setCondition(self, condition):
self.condition = condition
self.dataChanged.emit(QtCore.QModelIndex(), QtCore.QModelIndex())
def data(self, index, role=QtCore.Qt.DisplayRole):
if self.condition and role == QtCore.Qt.TextColorRole:
text = index.data(QtCore.Qt.DisplayRole)
if self.condition in text:
return QtGui.QColor("#58cd1c")
return super(FileSystemModel, self).data(index, role)
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None, useDelegate = False):
super(MainWidget, self).__init__(parent)
...
self.FileModel = FileSystemModel(self)
...
def changeCondition(self, text):
self.FileModel.setCondition(text)
I have a table with some records that are keyed using a very large number as the primary key. I have code similar to the following which uses QCompleter to autocomplete lookups in this table. It works, but the displayed completions are formatted using the scientific notation (1234567 => 1.23e6). I'd like to have my completions displayed as-is. In my opinion, I'd either need to cast the response from the query as a string (can't figure out how to do this) or set a property on the QLineEdit to disable scientific notation formatting (can't figure this out either). Any ideas?
class MyDialog(BaseObject, QtGui.QDialog):
def __init__(self, ... db=None):
super(MyDialog, self).__init__(parent, logger)
self.qsql_db = db
self.init_ui()
def mk_model(self, completer, pFilterModel, table_name, filter_=None):
model = QtSql.QSqlTableModel()
model.setTable(table_name)
if filter_:
model.setFilter(filter_)
model.select()
pFilterModel.setSourceModel(model)
completer.setModel(pFilterModel)
return model
def setModelColumn(self, completer, pFilterModel, column):
completer.setCompletionColumn(column)
pFilterModel.setFilterKeyColumn(column)
def mk_receipt_id_grid(self):
font = self.mk_font()
label_receipt_id = QtGui.QLabel(self)
label_receipt_id.setText("Order ID")
label_receipt_id.setFont(font)
self.text_edit_receipt_id = QtGui.QLineEdit()
self.text_edit_receipt_id.setFont(font)
label_receipt_id.setBuddy(self.text_edit_receipt_id)
self.formGridLayout.addWidget(label_receipt_id, 0, 0)
self.formGridLayout.addWidget(self.text_edit_receipt_id, 0, 1)
self.connect(self.text_edit_receipt_id,
QtCore.SIGNAL("editingFinished()"),
self.get_order_details)
completer = QtGui.QCompleter(self)
completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
pFilterModel = QtGui.QSortFilterProxyModel(self)
pFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
completer.setPopup(completer.popup())
self.text_edit_receipt_id.setCompleter(completer)
model = self.mk_model(completer, pFilterModel, "orders", "created_at > date_trunc('day', now())")
self.setModelColumn(completer, pFilterModel, model.fieldIndex("receipt_id"))
self.text_edit_receipt_id.textEdited.connect(pFilterModel.setFilterFixedString)
Screenshot of the issue:
One way to do this would be to set an item-delegate on the completer's view. The QStyledItemDelegate class has a displayText method that can be overridden, which makes implementing this quite easy.
Here is a simple demo:
import sys
from PySide import QtGui, QtCore
class ItemDelegate(QtGui.QStyledItemDelegate):
def displayText(self, data, locale):
if isinstance(data, (int, float)):
data = '%d' % data
return super(ItemDelegate, self).displayText(data, locale)
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
edit = QtGui.QLineEdit()
layout = QtGui.QVBoxLayout(self)
layout.addWidget(edit)
completer = QtGui.QCompleter(self)
model = QtGui.QStandardItemModel(self)
for value in (
17596767040000.0, 47993723466378568.0,
1219073478568475.0, 43726487587345.0,
29928757235623.0, 2245634345639486934.0,
):
item = QtGui.QStandardItem()
item.setData(value, QtCore.Qt.EditRole)
model.appendRow([item])
completer.setModel(model)
completer.popup().setItemDelegate(ItemDelegate(self))
edit.setCompleter(completer)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 50)
window.show()
sys.exit(app.exec_())
I have comboBox as one of widget and QspinBox as another widget. I want to disable QspinBox widget if we change option in available in comboBox widget. As an example in my code given below if I change option from option_1 to option_2, QspinBox widget need to get disabled. So how can I do it..?? Any help with example will be appreciated. My code is as follows,
from PyQt4 import QtCore, QtGui
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)
class Ui_tri_combobox(object):
def setupUi(self, tri_combobox):
tri_combobox.setObjectName(_fromUtf8("tri_combobox"))
tri_combobox.resize(686, 510)
self.centralWidget = QtGui.QWidget(tri_combobox)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.comboBox = QtGui.QComboBox(self.centralWidget)
self.comboBox.setGeometry(QtCore.QRect(50, 130, 221, 27))
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.comboBox.addItem(_fromUtf8(""))
self.comboBox.addItem(_fromUtf8(""))
self.spinBox = QtGui.QSpinBox(self.centralWidget)
self.spinBox.setGeometry(QtCore.QRect(360, 130, 251, 27))
self.spinBox.setObjectName(_fromUtf8("spinBox"))
tri_combobox.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(tri_combobox)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 686, 25))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
tri_combobox.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(tri_combobox)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
tri_combobox.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(tri_combobox)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
tri_combobox.setStatusBar(self.statusBar)
self.retranslateUi(tri_combobox)
QtCore.QMetaObject.connectSlotsByName(tri_combobox)
def retranslateUi(self, tri_combobox):
tri_combobox.setWindowTitle(_translate("tri_combobox", "tri_combobox", None))
self.comboBox.setItemText(0, _translate("tri_combobox", "option_1", None))
self.comboBox.setItemText(1, _translate("tri_combobox", "option_2", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
tri_combobox = QtGui.QMainWindow()
ui = Ui_tri_combobox()
ui.setupUi(tri_combobox)
tri_combobox.show()
sys.exit(app.exec_())
You're looking for the wonderful world of Qt signals and slots.
In simple code terms, this is the code you want executed when someone selects an element from the comboBox.
def dropdownSelect(self, index):
self.spinBox.setEnabled(not index)
Of course a non-toy example will use a more complicated series of if-statements, but the general idea is the same. In this case, index 0 is the first element, 1 is option_1, etc. Add this function to your Ui class.
Now link it by adding this line to setupUi:
self.comboBox.currentIndexChanged.connect(self.dropdownSelect)
Here's the documentation on this particular signal. What's going on here is that you're telling Qt that when the comboBox value is adjusted, you have a special handling function for that. The Qt core event loop handles managing all of that. The signal is a "pattern", that tells you which parameters you'll have access to in your slot.
So I have a QTableView and I only want to let column sorting on column 1 but not column2.
Naturally I tried to installEventFilter on QHeaderView or QTableView, but MouseButtonPress event is not being passed unless you installEventFilter on QApplication
Now if when eventFilter is called, the target object is always the top level widget although event.pos() is actually relative to the header or tablecell depending on where you click.
So we cannot use QHeaderView.rect().contains(event.pos()) to find out if the user clicks on the header because you get false positive when you click on the top edge of the very first table cell.
You can still however calculate this using globalPos but then your eventFilter's logic has to change when you change layout or add more widgets above the tableview.
I believe it is a bug that event.pos() returns the relative pos even the object argument always refer to the same top level widget.
A more logical API would be that there is a event.target() method to return the target where it calculates the relative pos.
But I don't see a target() method or a way to find the target in this event filter.
Maybe I'm missing something?
# -*- coding: utf-8 -*-
# pyqt windows 4.10.3
# python 2.7.5 32 bits
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = None
tableHeader = None
class MyModel(QAbstractTableModel):
def rowCount(self, QModelIndex_parent=None, *args, **kwargs):
return 2
def columnCount(self, QModelIndex_parent=None, *args, **kwargs):
return 2
def data(self, modelIndex, role=None):
if modelIndex.isValid():
row = modelIndex.row()
col = modelIndex.column()
if role == Qt.DisplayRole:
return "%02d,%02d" % (row, col)
def flags(self, index):
if index.isValid():
return Qt.ItemIsEnabled
def headerData(self, section, Qt_Orientation, role=None):
if role == Qt.DisplayRole and Qt_Orientation == Qt.Horizontal:
return "Column " + str(section+1)
class MyEventFilter(QObject):
def eventFilter(self, object, event):
if event.type() == QEvent.MouseButtonPress:
# object is always app/top level widget
print 'MouseButtonPress target :' + repr(object)
# even though event.pos() gives pos relative to the header when you click on header,
# and pos relative to table cells when you click on table cell
print repr(event.pos())
# however we can get the mouse's global position
print repr(event.globalPos())
# given the top level widget's geometry
print repr(app.activeWindow().geometry())
# and the table header's left, top and height
print repr(tableHeader.rect())
# we can find out whether mouse click is targeted at the header
print repr(event.globalPos().y() - app.activeWindow().geometry().y())
# BUT WHAT IF THE LAYOUT CHANGE OR WE ADD MORE WIDGETS ABOVE THE TABLEVIEW?
# WE HAVE TO ADJUST THE CALCULATION ABOVE!
return False
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = QMainWindow()
t = QTableView()
tableHeader = t.horizontalHeader()
t.setModel(MyModel())
w.setCentralWidget(t)
ef = MyEventFilter()
# installing in QMainWindow or QTableView won't catch MouseButtonPress
# https://qt-project.org/forums/viewthread/9347
#w.installEventFilter(ef)
#t.installEventFilter(ef)
app.installEventFilter(ef)
w.show()
sys.exit(app.exec_())
There's a much easier solution: reimplement the sort method of the model, and only permit sorting for the appropriate column.
Also, as an added refinement, use the sortIndicatorChanged signal of the header to restore the current sort indicator when appropriate.
Here's a demo script:
from PyQt4 import QtGui, QtCore
class TableModel(QtGui.QStandardItemModel):
_sort_order = QtCore.Qt.AscendingOrder
def sortOrder(self):
return self._sort_order
def sort(self, column, order):
if column == 0:
self._sort_order = order
QtGui.QStandardItemModel.sort(self, column, order)
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
QtGui.QWidget.__init__(self)
self.table = QtGui.QTableView(self)
model = TableModel(rows, columns, self.table)
for row in range(rows):
for column in range(columns):
item = QtGui.QStandardItem('(%d, %d)' % (row, column))
item.setTextAlignment(QtCore.Qt.AlignCenter)
model.setItem(row, column, item)
self.table.setModel(model)
self.table.setSortingEnabled(True)
self.table.horizontalHeader().sortIndicatorChanged.connect(
self.handleSortIndicatorChanged)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
def handleSortIndicatorChanged(self, index, order):
if index != 0:
self.table.horizontalHeader().setSortIndicator(
0, self.table.model().sortOrder())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window(5, 5)
window.show()
window.setGeometry(600, 300, 600, 250)
sys.exit(app.exec_())
I am using pyQt. How can I disable child items sorting in QTreeView/StandardItemModel?
You could use a QSortFilterProxyModel and reimplement its lessThan method.
Alternatively, create a subclass of QStandardItem and reimplement its less than operator.
Here's a simple example that demonstrates the latter approach:
from random import sample
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.view = QtGui.QTreeView(self)
self.view.setHeaderHidden(True)
self.model = QtGui.QStandardItemModel(self.view)
self.view.setModel(self.model)
parent = self.model.invisibleRootItem()
keys = range(65, 91)
for key in sample(keys, 10):
item = StandardItem('Item %s' % chr(key), False)
parent.appendRow(item)
for key in sample(keys, 10):
item.appendRow(StandardItem('Child %s' % chr(key)))
self.view.sortByColumn(0, QtCore.Qt.AscendingOrder)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.view)
class StandardItem(QtGui.QStandardItem):
def __init__(self, text, sortable=True):
QtGui.QStandardItem.__init__(self, text)
self.sortable = sortable
def __lt__(self, other):
if getattr(self.parent(), 'sortable', True):
return QtGui.QStandardItem.__lt__(self, other)
return False
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Call setSortingEnabled(bool) on your QTreeView instance. Here is the corresponding docu for c++ and here is the link to pyqt api docu for this function