以下小示例应用程序展示了您可以如何进行操作。基本上,有两个模型和两个视图。模型是 QGraphicsScene 和标准 QStandardItemModel,而视图是 QListView 和 QGraphicsView。
主要任务是通过使用信号和槽使两个模型保持同步。
可以使用添加按钮和上下文菜单修改模型。对于这个小应用程序,只能添加、删除和更改像素图的图片。添加其他操作(例如通过拖放移动项目)以及使用可检查操作和其他自定义用户角色隐藏/可见它们非常简单。
#include <QApplication>
#include <QFileDialog>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QHBoxLayout>
#include <QListView>
#include <QMenu>
#include <QPushButton>
#include <QStandardItemModel>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
auto frame = new QFrame;
frame->setLayout(new QHBoxLayout);
auto listView = new QListView;
frame->layout()->addWidget(listView);
auto graphicsView = new QGraphicsView;
frame->layout()->addWidget(graphicsView);
auto graphicsScene = new QGraphicsScene;
graphicsView->setScene(graphicsScene);
auto myModel = new QStandardItemModel;
auto btnAdd = new QPushButton("Add");
frame->layout()->addWidget(btnAdd);
QObject::connect(btnAdd, &QPushButton::clicked, [&]() {
auto item = new QStandardItem("Pixmap");
item->setData(QString("./data/test.png"), Qt::ItemDataRole::UserRole + 1);
myModel->appendRow(item);
});
listView->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
QObject::connect(listView, &QListView::customContextMenuRequested, [&](const QPoint& pos) {
auto index = listView->indexAt(pos);
QMenu menu;
auto remove = menu.addAction("Remove", [&]() {
myModel->removeRow(index.row(), index.parent());
});
if (!index.isValid()) remove->setEnabled(false);
auto changeImage = menu.addAction("Change...", [&]() {
auto file=QFileDialog::getOpenFileName(frame, "Select PNG file", "./data/", "(*.png)");
if (file.isEmpty()) return;
myModel->setData(index, file, Qt::ItemDataRole::UserRole + 1);
});
if (!index.isValid()) changeImage->setEnabled(false);
menu.exec(listView->mapToGlobal(pos));
});
QObject::connect(myModel, &QStandardItemModel::dataChanged, [&](const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles = QVector<int>()) {
if (auto item = myModel->itemFromIndex(topLeft)) {
if (auto pixItem = dynamic_cast<QGraphicsPixmapItem*>(graphicsScene->items()[topLeft.row()])) {
pixItem->setPixmap(QPixmap(item->data(Qt::ItemDataRole::UserRole + 1).toString()));
}
}
});
QObject::connect(myModel, &QStandardItemModel::rowsInserted, [&](const QModelIndex& parent, int first, int last) {
for (auto iter = first; iter <= last; iter++) {
auto index=myModel->index(iter, 0, parent);
auto pixmap=myModel->data(index, Qt::ItemDataRole::UserRole + 1).toString();;
auto item=graphicsScene->addPixmap(QPixmap(pixmap));
}
});
QObject::connect(myModel, &QStandardItemModel::rowsRemoved, [&](const QModelIndex& parent, int first, int last) {
auto items = graphicsScene->items();
for (auto iter = first; iter <= last; iter++) {
graphicsScene->removeItem(items[iter]);
}
});
listView->setModel(myModel);
frame->show();
return app.exec();
}