如何在Qt中从主菜单中选择文件?

如何在Qt中从主菜单中选择文件?,qt,qt5,signals-slots,qt5.4,qaction,Qt,Qt5,Signals Slots,Qt5.4,Qaction,我将文件夹中的所有文本文件加载到Qt应用程序的主菜单中 void MainWindow::loadFilesToMainMenu() { QString pathToDir("/myfiles"); QDirIterator it(pathToDir, QStringList() << "*.txt", QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { QString curPa

我将文件夹中的所有文本文件加载到Qt应用程序的主菜单中

void MainWindow::loadFilesToMainMenu() {
  QString pathToDir("/myfiles");

  QDirIterator it(pathToDir, QStringList() << "*.txt", QDir::Files, QDirIterator::Subdirectories);
  while (it.hasNext()) {
    QString curPathName = it.next();

    QStringList fileSegments = curPathName.split('/');
    QString curFileName = fileSegments.at(fileSegments.size() - 1);

    QAction* action = new QAction(tr(curFileName.toStdString().c_str()), this);

    action->setStatusTip(tr(curPathName.toStdString().c_str()));
    ui->menuFileList->addAction(action);

    // if new style selected?
    connect(action, SIGNAL(triggered()), this, SLOT(onLoadFile()));
  }
}
void主窗口::加载文件到主菜单(){
QString pathToDir(“/myfiles”);
QDirIterator it(pathToDir,QStringList()setstatistip(tr(curPathName.toStdString().c_str());
用户界面->菜单文件列表->添加操作(操作);
//如果选择了新样式?
连接(操作、信号(已触发())、此、插槽(onLoadFile());
}
}
在那里,我为文件夹“myfiles”中的所有文件创建QActions,并将每个QActions连接到插槽onLoadfile():

void主窗口::onLoadFile(){
QAction*action=qobject_cast(发送方());
如果(行动)
{

qDebug()来自@m.s.的答案很好地解决了我的问题

在尝试读取数据之前,应该使用QAction::setData()–m.s


@m.s.的答案很好地解决了我的问题

在尝试读取数据之前,应该使用QAction::setData()–m.s


在尝试读取数据之前,您应该使用作为旁注:为什么要用tr()包装文件路径字符串函数?这里没有真正需要翻译的东西…@m.s.这很有帮助,thanx!请您正确回答,以便我可以标记为已回答?@Mailerdaimon,因此我将仅在没有需要翻译的情况下使用tr?请参阅您在尝试读取数据之前应使用的附加说明:为什么要用tr()包装文件路径字符串函数?这里没有真正需要翻译的东西…@m.s.这很有帮助,thanx!请你正确回答,这样我就可以标记为已回答?@Mailerdaimon,所以我只在没有需要翻译的时候才使用tr?参见
void MainWindow::onLoadFile() {
  QAction *action = qobject_cast<QAction *>(sender());
  if (action)
  {
    qDebug() << " onLoadFile " << action->data().toString();
  }
}