Qt 通过打开文件对话框,实行拖拽到textEdit显示文本或者点击文件显示文本

ui->textEdit->setAcceptDrops(false);
    this->setAcceptDrops(true);
 connect(ui->action_O,&QAction::triggered,
            [=]()mutable
            {
                QString path=QFileDialog::getOpenFileName(this,
                                                          "open",
                                                          "/home",
                                                          "text files(*.txt *.c *.cpp *.h)"
                                                          );
                QFile file(path);
                QFileInfo fi=QFileInfo(path);
                if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
                {
                    QMessageBox::warning(this,"ERROR",QString("read file error:%1").arg(file.errorString()));
                }
                else
                {
                QTextStream txtinput(&file);
                QString line=txtinput.readLine();
                ui->textEdit->setText("");
                ui->textEdit->append(line);
                while(!line.isNull())
                {
                    line=txtinput.readLine();
                    ui->textEdit->append(line);
                }
                label->setText(fi.fileName());
                }

            }
            );
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if(event->mimeData()->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}



void MainWindow::dropEvent(QDropEvent *event)
{
    QListurls=event->mimeData()->urls();
    if(urls.isEmpty())
        return;
    QString filename1=urls.first().toLocalFile();
    if(filename1.isEmpty())
        return;
    QFileInfo fi=QFileInfo(filename1);
    QFile file(filename1);
    file.open(QIODevice::ReadOnly|QIODevice::Text);
    QTextStream txtinput(&file);
    QString line=txtinput.readLine();
    ui->textEdit->setText("");
    ui->textEdit->append(line);
    while(!line.isNull())
    {
        line=txtinput.readLine();
        ui->textEdit->append(line);
    }
    label->setText(fi.fileName());
}

你可能感兴趣的:(Qt 通过打开文件对话框,实行拖拽到textEdit显示文本或者点击文件显示文本)