Qt:QStandardItemModel を使用して QTableView にカスタム エディター (コンボ ボックス) を含める QItemDelegate を作成します。
-
12-12-2019 - |
質問
特定の列の各行にコンボ ボックスを表示するテーブルを Qt に実装する必要があります。
これまでのところ、この例に基づいています:http://doc.qt.nokia.com/4.7-snapshot/itemviews-spinboxdelegate.htmlそしてこの質問に関しては、QStandardItem + QComboBox無事にQItemDelegateを作成することができました。
私の問題は、main.cpp の main() 関数から実装するとすべて正常に動作しますが、Qt Designer にテーブルを挿入して使用すると、mainwindow.cpp の MainWindow クラスの関数内で使用するとうまく動作しないことです。 。
ヒントを教えてください。前もって感謝します!
main.cpp の委任 (2 番目の列をダブルクリックするとコンボ ボックスが表示され、うまく機能します):
QStandardItemModel model(4, 2);
QTableView tableView;
tableView.setModel(&model);
ComboBoxDelegate delegate;
tableView.setItemDelegateForColumn(1,&delegate);
tableView.horizontalHeader()->setStretchLastSection(true);
for (int row = 0 ; row < 4; ++row) {
for (int col = 0; col < 2; ++col) {
QModelIndex index = model.index(row, col, QModelIndex());
model.setData(index, QVariant((row+1) * (col+1)));
}
}
tableView.show();
mainwindow.cpp の代替 1 での委任 (空のテーブルが表示されます)
QStandardItemModel model(4,2);
ui->tablePoint->setModel(&model);
ComboBoxDelegate delegate;
ui->tablePoint->setItemDelegateForColumn(1,&delegate);
ui->tablePoint->horizontalHeader()->setStretchLastSection(true);
for (int row = 0 ; row < 4; ++row) {
for (int col = 0; col < 2; ++col) {
QModelIndex index = model.index(row, col, QModelIndex());
model.setData(index, QVariant((row+1) * (col+1)));
}
}
mainwindow.cpp の委任 代替 2 (テーブルは表示されますが、2 番目の列をダブルクリックしてもコンボ ボックスは表示されません。代わりに、通常のスピン ボックスが表示されます)。
QStandardItemModel* model = new QStandardItemModel(4,2);
ui->tablePoint->setModel(model);
ComboBoxDelegate delegate;
ui->tablePoint->setItemDelegateForColumn(1,&delegate);
ui->tablePoint->horizontalHeader()->setStretchLastSection(true);
for (int row = 0 ; row < 4; ++row) {
for (int col = 0; col < 2; ++col) {
QModelIndex index = model->index(row, col, QModelIndex());
model->setData(index, QVariant((row+1) * (col+1)));
}
}
解決
どちらの mainwindow.cpp の場合でも、表示するコードがコンストラクター内にあると仮定すると、モデルを割り当てるために古典的な「Java、Python、Perl、またはメモリ管理を気にしない言語から来ている」エラーを実行します。および/またはヒープではなくスタック上のデリゲート。
C++ では、スタックに割り当てられたもの (例: QStandardItemModel model(4,2);
) は関数から戻るときに破棄されますが、ヒープに割り当てられたもの (例: QStandardItemModel* model = new QStandardItemModel(4,2);
あなたまで生きます delete
それ)。ケース 1 は、スタックにものが割り当てられているため機能します。 main()
アプリの存続期間中存続します。
結論:ケース 3 の場合は、次のことを実行します。 ComboBoxDelegate* delegate = new ComboBoxDelegate();
そして ui->tablePoint->setItemDelegateForColumn(1,delegate);