其他分享
首页 > 其他分享> > 使用QTreeView在行中错误的文本对齐方式

使用QTreeView在行中错误的文本对齐方式

作者:互联网

我有一个QTreeView(使用PyQt4),使用下面的代码自定义和调整大小的图标,但是大小列显示错误的对齐/位置,如下所示:

        self.ui.treeView.setIconSize(QtCore.QSize(30,30))

        fileSystemModel = QtGui.QFileSystemModel(self.ui.treeView)
        custonIconProvider = CustomIconsProvider()
        fileSystemModel.setIconProvider(custonIconProvider)

        self.ui.treeView.setModel(fileSystemModel)
        self.ui.treeView.setRootIndex(fileSystemModel.setRootPath(forlderPath))

        self.ui.treeView.setColumnWidth(0, 250)
        self.ui.treeView.setColumnWidth(1, 70)
        self.ui.treeView.setColumnWidth(2, 70)

我搜索了http://pyqt.sourceforge.net/Docs/PyQt4/qtreeview.html文档以获得可能的修复,但找不到任何明显的信息.

解决方法:

解决此问题的一种方法是重新实现模型的data() method,以便TextAlignmentRole的值始终包含AlignVCenter标志:

# python3 or sip.setapi('QVariant', 2)

class FileSystemModel(QtGui.QFileSystemModel):
    def data(self, index, role):
        value = super(FileSystemModel, self).data(index, role)
        if role == QtCore.Qt.TextAlignmentRole and value is not None:
            value |= QtCore.Qt.AlignVCenter
        return value
# python2 or sip.setapi('QVariant', 1)

class FileSystemModel(QtGui.QFileSystemModel):
    def data(self, index, role):
        value = super(FileSystemModel, self).data(index, role)
        if role == QtCore.Qt.TextAlignmentRole and value.isValid():
            value = value.toInt()[0] | QtCore.Qt.AlignVCenter
        return value

标签:python,pyqt,pyqt4,text-alignment,qtreeview
来源: https://codeday.me/bug/20190629/1325276.html