PyQt4 setItemDelegateForRow 导致分段错误

Posted

技术标签:

【中文标题】PyQt4 setItemDelegateForRow 导致分段错误【英文标题】:PyQt4 setItemDelegateForRow causing segmentation fault 【发布时间】:2012-11-20 20:36:29 【问题描述】:

我正在尝试使用 QTableView.setItemDelegateForRow() 方法在我的 QTableView 上为每一行数据设置一个编辑器委托。当我在多行上设置委托时,它会导致 PyQt4 出现分段错误。它似乎至少部分与使用相同的变量来存储委托类的不同实例有关,如下所示:

# This code causes a segmentation fault
delegate = ListDelegate(choices0)
tableView.setItemDelegateForRow(0,delegate)
delegate = ListDelegate(choices1)
tableView.setItemDelegateForRow(1,delegate)

但是,如果我使用不同的变量,它似乎可以正常工作,例如:

# This code works to set the delegate by row
delegate0 = ListDelegate(choices0)
tableView.setItemDelegateForRow(0,delegate0)
delegate1 = ListDelegate(choices1)
tableView.setItemDelegateForRow(1,delegate1)

我有一个导致分段错误的代码示例,我将在最后包含该示例。我已经在 64 位的 Ubuntu Linux 和 Windows 7 上针对 python 2.7 进行了测试。

我意识到快速解决方法是只使用单独的变量,但在我的实际程序(不是这个示例代码)中,我试图在循环中设置委托,并使用字典或列表来存储委托似乎没有解决问题。

示例应用程序:

from PyQt4 import QtGui, QtCore
import sys

class PaletteListModel(QtCore.QAbstractListModel):

    def __init__(self, colors = [], parent = None):
        QtCore.QAbstractListModel.__init__(self,parent)
        self.__colors = colors

    # required method for Model class
    def rowCount(self, parent):
        return len(self.__colors)

    # optional method for Model class
    def headerData(self, section, orientation, role):
        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return QtCore.QString("Palette")
            else:
                return QtCore.QString("Color %1").arg(section)

        if role == QtCore.Qt.ToolTipRole:
            if orientation == QtCore.Qt.Horizontal:
                return QtCore.QString("Horizontal Header %s Tooltip" % str(section))
            else:
                return QtCore.QString("Vertical Header %s Tooltip" % str(section))


    # required method for Model class
    def data(self, index, role):
        # index contains a QIndexClass object. The object has the following
        # methods: row(), column(), parent()

        row = index.row()
        value = self.__colors[row]

        # keep the existing value in the edit box
        if role == QtCore.Qt.EditRole:
            return self.__colors[row].name()

        # add a tooltip
        if role == QtCore.Qt.ToolTipRole:
            return "Hex code: " + value.name()

        if role == QtCore.Qt.DecorationRole:
            pixmap = QtGui.QPixmap(26,26)
            pixmap.fill(value)

            icon = QtGui.QIcon(pixmap)

            return icon

        if role == QtCore.Qt.DisplayRole:

            return value.name()

    def setData(self, index, value, role = QtCore.Qt.EditRole):
        row = index.row()

        if role == QtCore.Qt.EditRole:
            color = QtGui.QColor(value)

            if color.isValid():
                self.__colors[row] = color
                self.dataChanged.emit(index, index)
                return True

        return False

    # implment flags() method
    def flags(self, index):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

class ListDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, colors = QtCore.QStringList(), parent = None):
        #super(ListDelegate, self).__init__()
        QtGui.QStyledItemDelegate.__init__(self,parent)
        self.__colors = colors
        #self.__current  = current

    def createEditor(self, parent, option, index):
        ed = QtGui.QComboBox(parent)
        ed.setEditable(True)

        # add each settings option to the combobox
        for s in self.__colors:
            ed.addItem(s)

        return ed


if __name__ == '__main__':


    app = QtGui.QApplication(sys.argv)
    app.setStyle("plastique")

    data = QtCore.QStringList()
    data << "one" << "two" << "three" << "four" << "five"

    tableView = QtGui.QTableView()
    tableView.show()

    red   = QtGui.QColor(255,0,0)
    green = QtGui.QColor(0,255,0)
    blue  = QtGui.QColor(0,0,255)

    model = PaletteListModel([red, green, blue])

    choices0 = QtCore.QStringList(["#FF0000","#00FF00","#0000FF"])
    choices1 = QtCore.QStringList(["#FF0000","#0000FF"])

    # This code works to set the delegate by row
    delegate0 = ListDelegate(choices0)
    tableView.setItemDelegateForRow(0,delegate0)
    delegate1 = ListDelegate(choices1)
    tableView.setItemDelegateForRow(1,delegate1)

    # This code causes a segmentation fault
    delegate = ListDelegate(choices0)
    tableView.setItemDelegateForRow(0,delegate)
    delegate = ListDelegate(choices1)
    tableView.setItemDelegateForRow(1,delegate)

    tableView.setModel(model)
    tableView.horizontalHeader()

    sys.exit(app.exec_())

Stacktrace(来自 Ubuntu 盒子)虽然我真的不知道如何解释它:

gdb python2.7-dbg
GNU gdb (GDB) 7.5-ubuntu
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /usr/bin/python2.7-dbg...done.
(gdb) run TestDelegateForRow.py
Starting program: /usr/bin/python2.7-dbg TestDelegateForRow.py
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7fffe6a78700 (LWP 12070)]
[New Thread 0x7fffe6277700 (LWP 12071)]
[New Thread 0x7fffe5442700 (LWP 12072)]

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff5ca7cf8 in ?? () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
(gdb) backtrace
#0  0x00007ffff5ca7cf8 in ?? () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#1  0x00007ffff5cb27f6 in QTableView::paintEvent(QPaintEvent*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#2  0x00007ffff64f54d3 in sipQTableView::paintEvent (this=0xfbfa60, a0=0x7fffffffc0a0) at sipQtGuipart2.cpp:35590
#3  0x00007ffff57be802 in QWidget::event(QEvent*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#4  0x00007ffff5b6db66 in QFrame::event(QEvent*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#5  0x00007ffff5c7959b in QAbstractItemView::viewportEvent(QEvent*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#6  0x00007ffff64fbc9b in viewportEvent (a0=0x7fffffffc0a0, this=0xfbfa60) at sipQtGuipart2.cpp:36150
#7  sipQTableView::viewportEvent (this=0xfbfa60, a0=0x7fffffffc0a0) at sipQtGuipart2.cpp:36142
#8  0x00007ffff524a6d6 in QCoreApplicationPrivate::sendThroughObjectEventFilters(QObject*, QEvent*) () from /usr/lib/x86_64-linux-gnu/libQtCore.so.4
#9  0x00007ffff576ee6c in QApplicationPrivate::notify_helper(QObject*, QEvent*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#10 0x00007ffff577330a in QApplication::notify(QObject*, QEvent*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#11 0x00007ffff67b62a6 in notify (a1=0x7fffffffc0a0, a0=0xe31b10, this=0xcfbcb0) at sipQtGuipart9.cpp:35916
#12 sipQApplication::notify (this=0xcfbcb0, a0=0xe31b10, a1=0x7fffffffc0a0) at sipQtGuipart9.cpp:35908
#13 0x00007ffff524a56e in QCoreApplication::notifyInternal(QObject*, QEvent*) () from /usr/lib/x86_64-linux-gnu/libQtCore.so.4
#14 0x00007ffff57ba524 in QWidgetPrivate::drawWidget(QPaintDevice*, QRegion const&, QPoint const&, int, QPainter*, QWidgetBackingStore*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#15 0x00007ffff57bb01f in QWidgetPrivate::paintSiblingsRecursive(QPaintDevice*, QList<QObject*> const&, int, QRegion const&, QPoint const&, int, QPainter*, QWidgetBackingStore*) ()
   from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#16 0x00007ffff57bae64 in QWidgetPrivate::paintSiblingsRecursive(QPaintDevice*, QList<QObject*> const&, int, QRegion const&, QPoint const&, int, QPainter*, QWidgetBackingStore*) ()
   from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#17 0x00007ffff57bae64 in QWidgetPrivate::paintSiblingsRecursive(QPaintDevice*, QList<QObject*> const&, int, QRegion const&, QPoint const&, int, QPainter*, QWidgetBackingStore*) ()
   from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#18 0x00007ffff57bae64 in QWidgetPrivate::paintSiblingsRecursive(QPaintDevice*, QList<QObject*> const&, int, QRegion const&, QPoint const&, int, QPainter*, QWidgetBackingStore*) ()
   from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#19 0x00007ffff57ba0b5 in QWidgetPrivate::drawWidget(QPaintDevice*, QRegion const&, QPoint const&, int, QPainter*, QWidgetBackingStore*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#20 0x00007ffff5988958 in ?? () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#21 0x00007ffff5988d1e in ?? () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#22 0x00007ffff57eb6aa in ?? () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#23 0x00007ffff57ec6bb in QApplication::x11ProcessEvent(_XEvent*) () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#24 0x00007ffff5813fa2 in ?? () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#25 0x00007ffff44b7ab5 in g_main_context_dispatch () from /lib/x86_64-linux-gnu/libglib-2.0.so.0
#26 0x00007ffff44b7de8 in ?? () from /lib/x86_64-linux-gnu/libglib-2.0.so.0
#27 0x00007ffff44b7ea4 in g_main_context_iteration () from /lib/x86_64-linux-gnu/libglib-2.0.so.0
#28 0x00007ffff5278bf6 in QEventDispatcherGlib::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) () from /usr/lib/x86_64-linux-gnu/libQtCore.so.4
#29 0x00007ffff5813c1e in ?? () from /usr/lib/x86_64-linux-gnu/libQtGui.so.4
#30 0x00007ffff52492bf in QEventLoop::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) () from /usr/lib/x86_64-linux-gnu/libQtCore.so.4
#31 0x00007ffff5249548 in QEventLoop::exec(QFlags<QEventLoop::ProcessEventsFlag>) () from /usr/lib/x86_64-linux-gnu/libQtCore.so.4
#32 0x00007ffff524e708 in QCoreApplication::exec() () from /usr/lib/x86_64-linux-gnu/libQtCore.so.4
#33 0x00007ffff677762b in meth_QApplication_exec_ (sipArgs=<optimized out>) at sipQtGuipart9.cpp:37856
#34 0x0000000000486b1a in PyCFunction_Call (func=<built-in method exec_ of QApplication object at remote 0xe891e0>, arg=(), kw=0x0) at ../Objects/methodobject.c:81
#35 0x0000000000526610 in call_function (pp_stack=0x7fffffffd960, oparg=0) at ../Python/ceval.c:4021
#36 0x00000000005213fb in PyEval_EvalFrameEx (f=Frame 0xb89c00, for file TestDelegateForRow.py, line 131, in <module> (), throwflag=0) at ../Python/ceval.c:2666
#37 0x0000000000523de9 in PyEval_EvalCodeEx (co=0xcbd510, globals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated), locals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated), args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at ../Python/ceval.c:3253
---Type <return> to continue, or q <return> to quit---
#38 0x0000000000519e56 in PyEval_EvalCode (co=0xcbd510, globals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated), locals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated)) at ../Python/ceval.c:667
#39 0x000000000055685c in run_mod (mod=0xb91aa8, filename=0x7fffffffe374 "TestDelegateForRow.py", globals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated), locals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated), flags=0x7fffffffde50, arena=0x9f8ae0) at ../Python/pythonrun.c:1365
#40 0x00000000005567e2 in PyRun_FileExFlags (fp=0xb3e1b0, filename=0x7fffffffe374 "TestDelegateForRow.py", start=257, globals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated), locals=
    'choices0': <QStringList at remote 0x10fc2e0>, 'choices1': <QStringList at remote 0x10fc380>, 'app': <QApplication at remote 0xe891e0>, 'delegate0': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89420>, 'delegate1': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe894e0>, 'blue': <QColor at remote 0x10fc240>, 'QtGui': <module at remote 0xcd2a20>, 'data': <QStringList at remote 0x10fc060>, '__package__': None, 'ListDelegate': <PyQt4.QtCore.pyqtWrapperType at remote 0xcfb6a0>, '__doc__': None, 'red': <QColor at remote 0x10fc100>, 'tableView': <QTableView at remote 0xe892a0>, '__builtins__': <module at remote 0x7ffff7fc5470>, '__file__': 'TestDelegateForRow.py', 'sys': <module at remote 0x7ffff7fc55a8>, '__name__': '__main__', 'PaletteListModel': <PyQt4.QtCore.pyqtWrapperType at remote 0xb955b0>, 'green': <QColor at remote 0x10fc1a0>, 'delegate': <ListDelegate(_ListDelegate__colors=<...>) at remote 0xe89660>, 'model': <PaletteListModel(_PaletteListModel__colors=[<...>, <...>, <...>]) at remote ...(truncated), closeit=1, flags=0x7fffffffde50) at ../Python/pythonrun.c:1351
#41 0x0000000000555002 in PyRun_SimpleFileExFlags (fp=0xb3e1b0, filename=0x7fffffffe374 "TestDelegateForRow.py", closeit=1, flags=0x7fffffffde50) at ../Python/pythonrun.c:943
#42 0x00000000005546b5 in PyRun_AnyFileExFlags (fp=0xb3e1b0, filename=0x7fffffffe374 "TestDelegateForRow.py", closeit=1, flags=0x7fffffffde50) at ../Python/pythonrun.c:747
#43 0x0000000000570290 in Py_Main (argc=2, argv=0x7fffffffe068) at ../Modules/main.c:639
#44 0x00000000004171fc in main (argc=2, argv=0x7fffffffe068) at ../Modules/python.c:23
(gdb) ^Z

当然,我们将不胜感激任何帮助或指导。

【问题讨论】:

我在 Win7 中没有遇到 SegFault。对于错误代码,我只是让row 0 回退到默认委托。我也很好奇保持listdict 的代表没有帮助。对于示例代码,将委托存储在 list 中可以使事情顺利进行。 【参考方案1】:

setItemDelegateForRow 的 Qt 文档对此非常清楚:

Any existing row delegate for row will be removed, but not deleted.
QAbstractItemView does not take ownership of delegate.

所以你已经诊断出你的问题,但没有解决它。

发生段错误是因为在初始化表视图之前正在对一些委托进行垃圾收集。

尝试创建一个 table-view 子类来保存其代表的内部列表:

...    

class TableView(QtGui.QTableView):
    def __init__(self):
        QtGui.QTableView.__init__(self)
        colours = [
            QtGui.QColor(255,0,0),
            QtGui.QColor(0,255,0),
            QtGui.QColor(0,0,255),
            ]
        self._delegates = [
            ListDelegate(["#FF0000","#00FF00","#0000FF"]),
            ListDelegate(["#FF0000","#0000FF"]),
            ]
        for row in range(len(colours)):
            self.setItemDelegateForRow(
                row, self._delegates[bool(row % 2)])
        self.setModel(PaletteListModel(colours))

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    app.setStyle("plastique")

    table = TableView()
    table.show()

    sys.exit(app.exec_())

【讨论】:

谢谢你,ekhumoro!被垃圾收集的代表是问题所在。在我对实际应用程序的测试中,它没有解决问题的原因是因为我在方法中初始化列表,并且一旦方法完成,列表就会被垃圾回收。

以上是关于PyQt4 setItemDelegateForRow 导致分段错误的主要内容,如果未能解决你的问题,请参考以下文章

如何让 PyQt4 与 PyCharm 一起工作

导入 PyQt4 模块

python 安装PyQt4

PyQT4 库的问题

PyQt4 - 拖放

运行 PyQt4 演示 --- 如何?