如何确保ItemDelegate正确定位

时间:2017-07-22 01:00:36

标签: python qt pyqt qt4 qt5

下面的代码会创建一个包含三个项目的QTableView。 双击任何项目会显示由QComboBox创建的QItemDelegate。问题是QComboBox显示在屏幕上的某个位置而不是预期的位置。代码有什么问题?

enter image description here

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *    
app = QApplication([])    

class ItemDelegate(QItemDelegate):
    def __init__(self, parent):
        QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        return QComboBox()


class Model(QAbstractTableModel):
    def __init__(self):
        QAbstractTableModel.__init__(self)
        self.items = [[1, 'one', 'ONE'], [2, 'two', 'TWO'], [3, 'three', 'THREE']]

    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsEditable

    def rowCount(self, parent=QModelIndex()):
        return 3

    def columnCount(self, parent=QModelIndex()):
        return 3

    def data(self, index, role):
        if not index.isValid():
            return

        if role in [Qt.DisplayRole, Qt.EditRole]:
            return self.items[index.row()][index.column()]


tableModel = Model()
view = QTableView()
view.setModel(tableModel)
view.setItemDelegate(ItemDelegate(view))

view.show()
app.exec_()

1 个答案:

答案 0 :(得分:1)

返回QComboBox(parent)时需要指定父对象:

enter image description here

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

app = QApplication([])


class ItemDelegate(QItemDelegate):
    def __init__(self, parent):
        QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        combo = QComboBox(parent)
        combo.addItems(['One', 'Two', 'Three'])
        return combo


class Model(QAbstractTableModel):
    def __init__(self):
        QAbstractTableModel.__init__(self)
        self.items = [[1, 'one', 'ONE'], [2, 'two', 'TWO'], [3, 'three', 'THREE']]

    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsEditable

    def rowCount(self, parent=QModelIndex()):
        return 3

    def columnCount(self, parent=QModelIndex()):
        return 3

    def data(self, index, role):
        if not index.isValid():
            return

        if role in [Qt.DisplayRole, Qt.EditRole]:
            return self.items[index.row()][index.column()]


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.clipboard = QApplication.clipboard()
        mainWidget = QWidget()
        self.setCentralWidget(mainWidget)

        mainLayout = QVBoxLayout()
        mainWidget.setLayout(mainLayout)

        view = QTableView()
        model = Model()
        view.setModel(model)
        view.setItemDelegate(ItemDelegate(view))

        column = 2
        for row in range(3):
            view.openPersistentEditor(view.model().index(row, column))

        mainLayout.addWidget(view)


view = MainWindow()
view.show()
app.exec_()