Starlays
Starlays

Reputation: 1109

Add QTableView to QComboBox

I'm retrieving a set of results from the database and I want to populate the QComboBox with the resulting columns from the database (each row of the QComboBox should have the same columns as database result) and after that I would like to be able to retrieve from one row of the QComboBox a specific column and use it further in the app. I'm thinking if it would be possible to add the QTableView to QComboBox. I'm want to do this because I want to add more meaning to the results in a way that some result columns are just plain numbers and other are the description information.

I found out that it would be possible to concatenate the result and populate the QComboBox but this will leave me with only one value for each row to work with and I have to explode the string to obtain the exact part that it is needed to work with.

Upvotes: 1

Views: 1206

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

The popup that comes by default is a QListView, this can be changed with any object that inherits from QAbstractItemView, and in this case a QTableView will be used for it to use the setView() method, the result when clicking only should return a item of the selected row, then to set the column to be displayed after being selected will use the method setModelColumn() indicating the position of the column, but before that the model is set to the QComboBox using the method setModel().

# my model
model = new QSqlTableModel;
model->setTable("person");
model->select();
# setModel
comboBox->setModel(model);
# select column
comboBox->setModelColumn(1);

QTableView  *view = new QTableView(this);
comboBox->setView(view);

Note: The model is set to QComboBox, not to QTableView. Also you could have problems with the width of QTableView, so we must resize, in my case use the following:

view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
view->setMinimumWidth(500);

The complete example can be found in the following link

Upvotes: 3

Related Questions