简体   繁体   中英

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 . 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).

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

#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. Look at the docs regarding QStyle , specifically for drawControl(..) . There's also a customised example I wrote for a question on SO which you can get an idea from.

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. Creating 'real' QCheckBox s is inefficient (in your example it will cause a massive memory leak), and becomes noticeably slow for large datasets. Whereas painting a 'fake' one only when required (ie visible) is very fast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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