QT开发中文网

c++ Qtreeview的某一项中添加按钮

要在C++的QTreeView的某一项中添加按钮,你可以使用自定义委托(Custom Delegate)来实现。下面是一个简单的示例代码:

首先,创建一个自定义的委托类 ButtonDelegate 继承 QItemDelegate,并重写 createEditor() 和 paint() 方法:

#include <QtWidgets>

class ButtonDelegate : public QItemDelegate
{
public:
    explicit ButtonDelegate(QObject *parent = nullptr)
        : QItemDelegate(parent) {}

    QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const override
    {
        if (index.column() == YOUR_BUTTON_COLUMN_INDEX)
        {
            // 创建一个 QPushButton 并设置其父对象为 parent
            QPushButton *button = new QPushButton(parent);
            return button;
        }

        return QItemDelegate::createEditor(parent, option, index);
    }

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
               const QModelIndex &index) const override
    {
        if (index.column() == YOUR_BUTTON_COLUMN_INDEX)
        {
            // 绘制按钮
            QStyleOptionButton buttonOption;
            buttonOption.rect = option.rect.adjusted(2, 2, -2, -2); // 调整按钮位置与大小
            buttonOption.text = "Button Text";
            
            QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter);
            return;
        }
        
        QItemDelegate::paint(painter, option, index);
    }
};

然后,在需要使用该委托的地方,例如在构造函数中对特定列应用该委托:

YourTreeViewClass::YourTreeViewClass(QWidget *parent) : QTreeView(parent)
{
    ButtonDelegate *delegate = new ButtonDelegate(this);
    setItemDelegateForColumn(YOUR_BUTTON_COLUMN_INDEX, delegate);
}

请将 YOUR_BUTTON_COLUMN_INDEX 替换为实际需要添加按钮的列索引。然后,当你在该列中显示时,会自动创建一个按钮,并且可以对其进行绘制和交互。

希望这个例子对你有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=6071

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?