我有一个 QTableView *tableView。当用户在 tableView 中选择文件/文件夹并右键单击 -> 选择“打印这些项目”时,我希望我的程序将这些名称打印到文本文件中或分配给字符串。我怎样才能做到这一点?谢谢。
主窗口.h:
private slots:
void showContextMenuRequested(QPoint pos);
frmainwindow.cpp:
#include "frmainwindow.h"
#include "ui_frmainwindow.h"
FrMainWindow::FrMainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::FrMainWindow)
{
ui->setupUi(this);
model1->setRootPath("c:\\");
ui->tableView->setModel(model1);
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this,
SLOT (showContextMenuRequested(QPoint)));
}
FrMainWindow::~FrMainWindow()
{
delete ui;
}
void FrMainWindow::showContextMenuRequested(QPoint pos)
{
QMenu *contextMenu = new QMenu(this);
contextMenu->addAction(new QAction("Print these items", this));
contextMenu->popup(ui->tableView->viewport()->mapToGlobal(pos));
}
最佳答案
首先,将您的操作连接到一个处理槽:
QAction* action = new QAction("Print these items", this);
connect(action, SIGNAL(triggered(), this, SLOT(printItems())));
然后您可以访问选定的索引 tableView->selectionModel()->selectedIndexes()
并使用这些索引访问数据 model1->data(index)
:
void printItems()
{
QFile file(QLatin1String("file.txt"));
file.open(QIODevice::WriteOnly);
QModelIndexList indexes = ui->tableView->selectionModel()->selectedIndexes();
foreach (QModelIndex index, indexes)
{
file.write(model1->data(index).toString().toLatin1());
}
}
关于c++ - (Qt C++) 如何从 QTableView 将选定的文件/文件夹打印到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25616423/