Linux_Qt_文管的文件打开方式

本文详细讲述了如何使用QFile读取mimeinfo.cache文件,通过正则表达式筛选MIME类型,并根据每个MIME关联的应用设置自定义菜单,展示了Qt中文件操作与动态菜单构建的过程。

 

QFile *file = new QFile;
file->setFileName("/usr/share/applications/mimeinfo.cache");
bool ok = file->open(QIODevice::ReadOnly);
if (ok) {
    QTextStream TS(file);
    QString s = TS.readAll();
    file->close();
    QStringList SL = s.split("\n");
    SL = SL.filter(MIME + "=");
    QMenu *menu_openwith = new QMenu(this);
    action_openwith->setMenu(menu_openwith);
    for (int i=0; i<SL.length(); i++) {
        s = SL.at(i);
        //qDebug() << s;
        s = s.mid(s.indexOf("=")+1);
        //qDebug() << s;
        QStringList SL1 = s.split(";");
        SL1.removeAll("");
        for (int j=0; j<SL1.length(); j++) {
            QString desktop = "/usr/share/applications/" + SL1.at(j);
            QString sExec = readSettings(desktop, "Desktop Entry", "Exec");
            sExec = sExec.left(sExec.indexOf(" "));
            QString sName = readSettings(desktop, "Desktop Entry", "Name");
            QString sIcon = readSettings(desktop, "Desktop Entry", "Icon");
            QAction *action = new QAction(menu_openwith);
            action->setText(sName);
            QIcon icon;
            if (sIcon == "")
                sIcon = "applications-system-symbolic";
            if (QFileInfo(sIcon).isFile()) {
                icon = QIcon(sIcon);
            } else {
                icon = QIcon::fromTheme(sIcon);
            }
            action->setIcon(icon);
            connect(action, &QAction::triggered, [=](){
                QProcess *process = new QProcess;
                process->setWorkingDirectory(path);
                qDebug() << sExec;
                process->setProgram(sExec);
                process->setArguments(QStringList() << filepath);
                bool b = process->startDetached();
                qDebug() << b;
            });
            menu_openwith->addAction(action);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值