我正在尝试为QTreeWidget
添加一个选项以进行多行编辑,我认为这将需要一个QTextEdit
。问题在于,我在网上找到的示例不起作用。
The answers I've found都指向使用tree.setItemWidget(item, column, widget)
,但如果我添加该行,则根本不会显示该窗口。在这种情况下我怎么了?
这是我的示例代码中存在的问题:
import sys
from Qt import QtWidgets, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None, **kwargs):
super(MainWindow, self).__init__(parent, **kwargs)
#Add tree widget to window
tree = QtWidgets.QTreeWidget()
tree.setHeaderItem(QtWidgets.QTreeWidgetItem(['col1', 'col2']))
self.setCentralWidget(tree)
#Create items
topLevelButton = QtWidgets.QPushButton('button')
topLevelItem = QtWidgets.QTreeWidgetItem(['test button', 'line edit'])
topLevelItem.setFlags(topLevelItem.flags() | QtCore.Qt.ItemIsEditable)
#Add items to tree widget
tree.addTopLevelItem(topLevelItem)
tree.setItemWidget(topLevelItem, 0, topLevelButton) #the window will not load if this line is not commented out
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
app.setActiveWindow(window)
window.show()
sys.exit(app.exec_())
我已经在PySide (2.7)
和PySide2 (3.7)
中尝试过。
编辑:至少对于Python 3来说,PySide2似乎是一个问题,无论如何强制PyQt5都可以解决。由于无法真正安装PyQt4,我仍然无法使用Python 2启动。
编辑2:如果您在使用Nuke
的程序中使用它,实际上会导致崩溃,如果我无法弄清楚,我可能需要问一个更具体的问题从这个。
答案 0 :(得分:1)
抱歉,PyQt5正在运行。
import sys
#from Qt import QtWidgets, QtCore
from PyQt5 import QtWidgets, QtCore # <---
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None, **kwargs):
super(MainWindow, self).__init__(parent, **kwargs)
# Add tree widget to window
tree = QtWidgets.QTreeWidget()
tree.setHeaderItem(QtWidgets.QTreeWidgetItem(['col1', 'col2']))
self.setCentralWidget(tree)
# Create items
topLevelButton = QtWidgets.QPushButton('button')
topLevelItem = QtWidgets.QTreeWidgetItem(['test button', 'line edit'])
topLevelItem.setFlags(topLevelItem.flags() | QtCore.Qt.ItemIsEditable)
# Add items to tree widget
tree.addTopLevelItem(topLevelItem)
tree.setItemWidget(topLevelItem, 0, topLevelButton) # ??? the window will not load if this line is not commented out
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
app.setActiveWindow(window) # ???
window.show()
sys.exit(app.exec_())