将 QTableView 添加到 QComboBox

Add QTableView to QComboBox

我正在从数据库中检索一组结果,我想用数据库中的结果列填充 QComboBox(QComboBox 的每一行都应具有与数据库结果相同的列),然后我会希望能够从 QComboBox 的一行中检索特定列并在应用程序中进一步使用它。我在想是否可以将 QTableView 添加到 QComboBox。我想这样做是因为我想通过一些结果列只是普通数字而其他列是描述信息的方式为结果添加更多含义。

我发现可以连接结果并填充 QComboBox 但这将使每一行只有一个值可供使用,我必须分解字符串以获得它的确切部分需要一起工作。

默认出现的弹出窗口是 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);

注意:模型设置为QComboBox,不是QTableView。 QTableView 的宽度也可能有问题,所以我们必须调整大小,在我的例子中使用以下内容:

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

完整的例子可以在下面找到link