QT QFileDialog文件选择对话框
选择txt或者cpp文件,读取内容并显示
参考:
QT写入文件与读取文件内容_qt往一个文件写东西-CSDN博客
#include "QtFilePreview.h"
#include "qfiledialog.h"
#include "qfile.h"
#include "qtextstream.h"
#include "qfileinfo.h"
QtFilePreview::QtFilePreview(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
ui.textEdit_preview->setReadOnly(true);
ui.label_preview->setScaledContents(true);
connect(ui.pushButton_open, &QPushButton::clicked, this, [=] {
QString fileName = QFileDialog::getOpenFileName(this,tr("Open File"),"",tr("All Files(*.*)"));
if (!fileName.isEmpty())
{
QFile file(fileName);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream in(&file);
ui.textEdit_preview->setText(in.readAll());
file.close();
QFileInfo fileInfo(fileName);
QPixmap pixmap(fileInfo.absolutePath());
ui.label_preview->setPixmap(pixmap.scaled(ui.label_preview->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation ));
}
}
});
}
QtFilePreview::~QtFilePreview()
{}