Search code examples
qtqtreeviewqcombobox

qt QComboBox setView to QTreeView can not do setCurrentIndex


treecombobox.h

#ifndef TREECOMBOBOX_H
#define TREECOMBOBOX_H

#include <QComboBox>
#include "QAbstractItemView"
#include "QTreeView"

class TreeComboBox : public QComboBox
{
    Q_OBJECT
public:
    explicit TreeComboBox(QWidget *parent = 0);
    ~TreeComboBox();

protected:
    QTreeView* internalView;

signals:

public slots:

};

#endif // TREECOMBOBOX_H

treecombobox.cpp

#include "treecombobox.h"

TreeComboBox::TreeComboBox(QWidget *parent) :
    QComboBox(parent){

    this->internalView = new QTreeView( parent );
    this->setView( this->internalView );
    QAbstractItemModel* model = this->internalView->model();
    model->insertRows( 0, 2 );
    model->setData( model->index(0,0), "First" );
    model->setData( model->index(1,0), "Second" );
    this->view()->setCurrentIndex( model->index(1,0) );
}


TreeComboBox::~TreeComboBox(){
    if( this->internalView ){
        delete this->internalView;
        this->internalView = 0;
    }
}

I want to show the second item, but qt gives me the first item. this->view()->currentIndex() gives me the correct model index, but the widget doesn't display correct content.

What I want is a combo box with tree view popup box. The popup box works fine. The only problem is it goes wrong when I try to choose an item automatic in program.

Can some one tell me how to do?


Solution

  • A few time ago was meeting with the same question.

    Can offer next solution (based on native QComboBox code and some internet stuff):

    TreeComboBox::presetIndex(QModelIndex index)
    {
    
            setRootModelIndex(index.parent());
            setModelColumn(index.column());
            setCurrentIndex(index.row());
            setRootModelIndex(QModelIndex());
            view->setCurrentIndex(index);
    }
    

    Sorry about formatting, first time and still not know how to make code-highlights here.