QComboBox
特定の列の各行にを表示するテーブルを Qt に実装する必要があります。
この質問に基づいて: QStandardItem + QComboBoxを作成することに成功しましたQItemDelegate
。その例では、QComboBox
コンテンツはクラスで静的に定義されComboBoxDelegate
ていますが、私の場合はQComboBox
、が作成される関数内でコンテンツを定義する必要がありますQStandardItemModel
。
モデルはMainWindow
クラス メソッド内で定義されます。
void MainWindow::fooHandler() {
QStandardItemModel* mymodel = new QStandardItemModel;
ui->tablePoint->setModel(mymodel);
ComboBoxDelegate* delegate=new ComboBoxDelegate;
ui->tablePoint->setItemDelegateForColumn(2,delegate);
QStringList Pets;
Pets.append("cat");
Pets.append("dog");
Pets.append("parrot");
// So far this is how I tried to store data under `Qt::UserRole` in "mymodel":
QModelIndex idx = mymodel->index(0, 2, QModelIndex());
mymodel->setData(idx,QVariant::fromValue(Pets), Qt::UserRole);
//Now i fill the table with some values...
QList< QStandardItem * > items;
items.clear();
items << new QStandardItem("col0");
items << new QStandardItem("col1");
items << new QStandardItem("parrot");
items << new QStandardItem("col3");
mymodel->appendRow(items);
items.clear();
items << new QStandardItem("col0");
items << new QStandardItem("col1");
items << new QStandardItem("cat");
items << new QStandardItem("col3");
mymodel->appendRow(items);
}
ComboBox
次に、デリゲート クラスからコンテンツを復元できるはずです。
void ComboBoxDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::EditRole).toString();
QComboBox *cBox = static_cast<QComboBox*>(editor);
if(index.column()==2) {
QModelIndex idx = index.model()->index(0, 2, QModelIndex());
cBox->addItem( index.model()->data(idx,Qt::UserRole).toStringList().at(0) );
cBox->addItem( index.model()->data(idx,Qt::UserRole).toStringList().at(1) );
cBox->addItem( index.model()->data(idx,Qt::UserRole).toStringList().at(2) );
}
cBox->setCurrentIndex(cBox->findText(value));
}
プロジェクトは正常にコンパイルされますが、セルをクリックしてQComboBox
値を変更すると、プログラムがクラッシュし、「無効なパラメーターが C ランタイム関数に渡されました」というメッセージが表示されます。