前言:在原有的工具(只可以一次选一个文件)基础上支持一次性多个文件选择,并将选择的文件路径显示在listView上,并且可以支持右键删除文件路径。
1、支持连续添加文件(下面这个是槽函数),setModel函数:
QStringList fpath = QFileDialog::getOpenFileNames(this, "Please Select PS File", ".", "PS File(*.ps);;All Files(*.*)");
QStringList pathlist = m_slFilePath; // QStringList类的成员变量
QStringListModel *modelitem;
for(int i=0; i<fpath.length(); i++)
{
bool flag = true;
for(int j=0; j<pathlist.length(); j++)
{
if(pathlist.at(j) == fpath.at(i))
{
flag = false;
QMessageBox::warning(this, "Error", "The file you selected is duplicated");
return ;
}
}
if(flag)
m_slFilePath.append(fpath.at(i));
}
modelitem = new QStringListModel(m_slFilePath);
m_plistView->setModel(modelitem);//m_plistView是QListView类的成员变量,这个函数就是把list添加到listView中。
2、右击出现菜单(customContextMenuRequested信号),删除选中的文件路径(removeRow函数):
connect(m_plistView,SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(slotRightClickDelete(const QPoint&)));//信号与槽函数,还要有m_plistView->setContextMenuPolicy(Qt::CustomContextMenu);这个函数,不然不触发信号。
//slotRightClickDelete:
if(!((m_plistView->selectionModel()->selectedIndexes()).empty()))//只能在有内容的情况下右键有效果
{
QMenu *cmenu = new QMenu(m_plistView);
QAction *pDeleteAction = cmenu->addAction("Delete");
connect(pDeleteAction, SIGNAL(triggered(bool)), this, SLOT(slotDeleteFile()));
cmenu->exec(QCursor::pos());
m_plistView->selectionModel()->clear();
}
//slotDeleteFile:
QString currentText = m_plistView->currentIndex().data(m_plistView->currentIndex().row()).toString();
for(int i=0; i<m_slFilePath.length(); i++)
{
if(m_slFilePath.at(i) == currentText)
{
m_slFilePath.removeAt(i);
}
}
m_plistView->model()->removeRow(m_plistView->currentIndex().row());