我试图在QTableView中显示一个QListView,所以我创建了一个委托,并在paint事件中我做了
<ul>
并获得正确的尺寸大小我做:
QListWidget list;
list.addItem(index.data().toString());
list.addItems({"1", "2", "3", "4"});
list.resize(option.rect.width(), option.rect.height());
painter->save();
painter->setClipRect(option.rect);
painter->translate(option.rect.topLeft());
list.render(painter);
painter->restore();
这将呈现列表,但我无法使用滚动条,并且单元格大小不会更改以显示完整列表。有没有办法让Qt正确渲染?
答案 0 :(得分:1)
我认为实现你想要的东西很难。只需使用setIndexWidget
即可。例如:
QListWidget *list = new QListWidget;
list->addItems({"1", "2", "3", "4"});
QTableView *table = new QTableView;
QStandardItemModel *model = new QStandardItemModel(10,10);
table->setModel(model);
table->setIndexWidget(table->model()->index(0,0), list);
table->resizeRowsToContents();
table->show();
在这种情况下,它是完整的小部件,具有滚动支持和其他功能。
修改强>
是的,当然。看另一个例子:
QListWidget *list = new QListWidget;
list->addItems({"1", "2", "3", "4"});
QTableView *table = new QTableView;
QStandardItemModel *model = new QStandardItemModel(10,10);
QStandardItem *it1 = new QStandardItem("example1");
QStandardItem *it2 = new QStandardItem("example2");
model->setItem(1,0,it1);
model->setItem(2,0,it2);
table->setModel(model);
table->setIndexWidget(table->model()->index(0,0), list);
table->resizeRowsToContents();
table->show();
for(int i = 0; i < model->rowCount(); i++)
{
qDebug() << table->model()->index(i,0).data();
}
<强>输出:强>
QVariant(Invalid) //because it is a widget, there is no data in display role
QVariant(QString, "example1") //our data
QVariant(QString, "example2")
QVariant(Invalid) //because we didn't set data and so on...
QVariant(Invalid)
...