QT 通过QFileDialog选择一个txt文件并打开

(1) 首先需要包含头文件
    #include "QFileDialog"
    #include "QDebug"
    
(2) 实际代码
    void MainWindow::on_pushButton_clicked()
    {
        QStringList infoList;
        //获取文件名
        QString fileName = QFileDialog::getOpenFileName(
                    this,
                    tr("open a file."),
                    "",
                    tr("text(*.txt);;video files(*.avi *.mp4 *.wmv);;All files(*.*)"));
                    
        if (fileName.isEmpty())
        {
            QMessageBox::warning(this, "Warning!", "Failed to open the video!");
        }
        else
        {
            QFile file(fileName);
            //打开文件
            if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                qDebug()<<"Can't open the file!"<<endl;
            }

            //循环读取txt  并打印 
            while(!file.atEnd())
            {
                QByteArray line = file.readLine();
                QString str(line);
                if(str.contains("\n"))
                {
                    str = str.replace("\n" , "");
                }

                qDebug()<< str;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_14874791/article/details/106372472