简体   繁体   English

QTreeView自定义列

[英]QTreeView custom column

I need show files from QFileSystemModel in QTreeView and customize that tree to show one more column with QCheckBox , so user can pick 0..N files from that QTreeView . 我需要在QTreeView显示来自QFileSystemModel文件,并自定义该树以使用QCheckBox显示更多列,因此用户可以从该QTreeView选择0..N个文件。 I read doc from Qt to understand model/view architecture and i am now in my code at point, where i have custom delegate CustomItemDelegate for specific column, but actually i don't know how to create QCheckBox in paint method of my custom delegate (to be more specific i know how, but this is 99% bad way). 我从Qt阅读文档以了解模型/视图架构,现在我在代码中处于特定位置,对于特定列,我具有自定义委托CustomItemDelegate ,但实际上我不知道如何在我的自定义委托的paint方法中创建QCheckBox (更具体地说,我知道怎么做,但这是99%的坏方法)。

customitemdelegate.h customitemdelegate.h

#ifndef CUSTOMITEMDELEGATE_H
#define CUSTOMITEMDELEGATE_H

#include <QStyledItemDelegate>

class CustomItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit CustomItemDelegate(QObject *parent = 0);
    void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const;

signals:

public slots:

};

#endif // CUSTOMITEMDELEGATE_H

customitemdelegate.cpp customitemdelegate.cpp

#include "customitemdelegate.h"
#include <QCheckBox>
#include <iostream>
#include <QTreeView>

using namespace std;

CustomItemDelegate::CustomItemDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

 void CustomItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const {

     ((QTreeView *)parent())->setIndexWidget(index, new QCheckBox());

 }

You don't create a QCheckbox , you paint one using the current style. 您无需创建QCheckbox ,而是使用当前样式绘制一个。 Look at the docs regarding QStyle , specifically for drawControl(..) . 查看有关QStyle文档 ,专门针对drawControl(..) There's also a customised example I wrote for a question on SO which you can get an idea from. 还有一个我针对SO 问题编写的自定义示例,您可以从中得到启发。

Mouse handling has to be handled by the view (because the control doesn't actually exist), and for most styles that will include mouse-over updating. 鼠标处理必须由视图处理(因为该控件实际上不存在),并且对于大多数样式,其中包括鼠标悬停更新。

It is a bit of a pain (things may have gotten easier in v5.0+, I last did this in v4.8), but it's well worth it. 有点痛苦(在v5.0 +中事情可能变得更容易了,我上一次在v4.8中做到了),但这是值得的。 Creating 'real' QCheckBox s is inefficient (in your example it will cause a massive memory leak), and becomes noticeably slow for large datasets. 创建“真实的” QCheckBox效率低下(在您的示例中,它将导致大量的内存泄漏),并且对于大型数据集而言明显变慢。 Whereas painting a 'fake' one only when required (ie visible) is very fast. 而仅在需要(即可见)时才绘画“假”的东西非常快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM