PDA

View Full Version : Automatically add items to a QComboBox (Qt4)



darkadept
18th May 2006, 16:16
Hello everyone,

I have a QComboBox that is connected to a QSqlTableModel (via setModel). The combobox displays the items from the database just fine. I have the editable and autocomplete properties of the combobox set to true. I want the user to be able to either: 1) select an existing item from the list, 2) start typing and let the autocomplete select an existing item, and 3) add a new item if it doesn't already exist.

I've got 1) and 2) working but the adding of new items doesn't seem to work well. I know that the QComboBox is not a proper 'View' in Qt4, so maybe I'm not doing things right.

Thanks in advance for the help.

wysota
18th May 2006, 17:10
Can you show us some code?

darkadept
19th May 2006, 16:32
Actually I may have figured it out (after much debugging) although I have no idea if i'm doing it the "right" way. Is there a better way to do this?

Here is what I have done:

In the constructor to my window i create my model and assign it to my combobox. I then connect the dataChanged signal from the model, to a slot that submits the data to the database.

In QtDesigner I have these properties set on the combobox:
editable = true
autoCompletion = true
insertPolicy = QComboBox::InsertAtBottom
modelColumn = true



//Constructor
MyWindow::MyWindow(QWidget *parent) : QWidget(parent)
{
setupUi(this); //i'm using Qt Designer for my GUI design.

myModel = new QSqlTableModel(this);
myModel->setTable("mydatabasetable");
myModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
myModel->select();

myComboBox->setModel(myModel);
myComboBox->setModelColumn(1); //collumn 0 is an auto ID, column 1 is text, which i want displayed

connect(myModel, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(myModelDataChanged(const QModelIndex &, const QModelIndex &)));
}

//DataChanged Slot
void MyWindow::myModelDataChanged(const QModelIndex &, const QModelIndex &)
{
myModel->submitAll();
}


I've tried different edit strategies and it seems that only OnManualSubmit works.