Reputation: 21
I am trying to write a PyQt5 widget which will be a basic preset manager inside an application. I am trying to use the QTreeWidget to display the structure of each type. I have this weird issue, where I see an extra QTreeWidget with a column named "1" outside my QTreeWidget. I have attached a picture (sorry, I could not take a screenshots) and the code. I have also noticed that this does not happen if I don't use classes.
Here's my test code showing the problem:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MyTree(QtWidgets.QTreeWidget):
def __init__(self, parent = None):
super(self.__class__, self).__init__(parent)
boxLayout = QtWidgets.QVBoxLayout()
treeWidget = QtWidgets.QTreeWidget()
treeWidget.setHeaderLabels(['Preset Name'])
treeWidget.setColumnCount(1)
items = []
for i in range(10):
items.append(QtWidgets.QTreeWidgetItem(["item {0}".format(i)]))
treeWidget.insertTopLevelItems(0, items)
boxLayout.addWidget(treeWidget)
self.setLayout(boxLayout)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = MyTree()
w.show()
sys.exit(app.exec_())
That's what I see:
My best guess that it's the layout that's causing it, because if I just create the QTreeWidget like so:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
app = QtWidgets.QApplication(sys.argv)
treeWidget = QtWidgets.QTreeWidget()
treeWidget.setHeaderLabels(['Preset Name'])
treeWidget.setColumnCount(1)
items = []
for i in range(10):
items.append(QtWidgets.QTreeWidgetItem(["item {0}".format(i)]))
treeWidget.insertTopLevelItems(0, items)
treeWidget.show()
sys.exit(app.exec_())
That's what I see:
Any ideas how to get it showing like the second image, from a class?
Any help is greatly appreciated
Upvotes: 1
Views: 313
Reputation: 243897
The error is simple: Your window (MyTree) is an empty QTreeWidget that has another QTreeWidget inside, so "1" belongs to the empty QTreeWidget.
There are 2 possible solutions:
No user as base class to QTreeWidget
class MyTree(QtWidgets.QWidget):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
treeWidget = QtWidgets.QTreeWidget()
treeWidget.setHeaderLabels(["Preset Name"])
treeWidget.setColumnCount(1)
items = []
for i in range(10):
items.append(QtWidgets.QTreeWidgetItem(["item {0}".format(i)]))
treeWidget.insertTopLevelItems(0, items)
boxLayout = QtWidgets.QVBoxLayout(self)
boxLayout.addWidget(treeWidget)
Do not nest a new QTreeWidget
class MyTree(QtWidgets.QTreeWidget):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.setHeaderLabels(["Preset Name"])
self.setColumnCount(1)
items = []
for i in range(10):
items.append(QtWidgets.QTreeWidgetItem(["item {0}".format(i)]))
self.insertTopLevelItems(0, items)
Upvotes: 1