如何使用Qt代理进行自定义绘制?

2024-10-04 03:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重写当一个项拖到qtreewigetitems上时绘制它们的方式。我已经覆盖了拖动事件来设置Qt.UserRole我要绘制的qtreewiggetItems的数据设置为1。在Item委托中,我读取UserRole并相应地绘制。在

我的自定义绘画完全按照预期显示(即粗体线条);但是,我无法想出如何在不抑制所有其他绘画(即文本等)的情况下抑制标准画家拖动的绘图(即小矩形)。在

任何想法都将不胜感激。在

alt text

例如

def dragMoveEvent(self, event):
    pos = event.pos()
    item = self.myTreeWidget.itemAt(pos)

    # If hovered over an item during drag, set UserRole = 1
    if item:
        index = self.myTreeWidget.indexFromItem(item)
        self.myTreeWidget.model().setData(index, 1, Qt.UserRole)

    # reset UserRole to 0 for all other indices
    for i in range(self.myTreeWidget.model().rowCount()):
        _index = self.myTreeWidget.model().index(i, 0)
        if not item or index != _index:
            self.myTreeWidget.model().setData(_index, 0, Qt.UserRole)


class MyDelegate(QStyledItemDelegate):

    def paint( self, painter, option, index ):
        QStyledItemDelegate.paint(self, painter, option, index)
        painter.save()
        data = index.model().data( index, Qt.UserRole ).toInt()
            # if UserRole = 1 draw custom line
        if data[1] and data[0] == 1:
            line = QLine( option.rect.topLeft(), option.rect.topRight() )
            painter.drawLine( line )
        painter.restore()

Tags: posselfdataindexmodelifline绘制
1条回答
网友
1楼 · 发布于 2024-10-04 03:28:43

使用c++使用qt很容易解决这一问题:只要通过element参数接收到QStyle::PEüu IndicatorItemViewItemDrop常量,您就可以定义一个新样式,重写drawPrimitive方法,并在那里进行自定义绘制(或者什么都不做)。下面是一个例子:

class TestStyle : public QProxyStyle
{
public:
    TestStyle(QStyle *baseStyle = 0) : QProxyStyle(baseStyle) {}

    void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
    {
        if (element == QStyle::PE_IndicatorItemViewItemDrop)
        {
            //?? do nothing or do custom painting here
        }
        else
        {
            QProxyStyle::drawPrimitive(element, option, painter, widget);
        }
    }
};

.. 

ui->treeView->setStyle(new TestStyle(ui->treeView->style()));

现在坏消息是pyqt似乎对QProxyStyle一无所知;看起来它没有被包装在那里,所以为了让它工作,您需要自己包装样式类。在

另一个解决方案是创建一个自定义的QTreeView子体并重写其paintEvent方法。默认实现是调用drawTree和paintDropIndicator;其中paintDropIndicator负责拖放指示器,drawTree呈现树项。drawTree受到保护,您可以从paintEvent调用:

^{2}$

这将抑制默认的拖放指示器。如果您在将其转换为python时遇到困难,请告诉我。在

希望这对你有帮助,谢谢

相关问题 更多 >