Qt: Implement simple filter in log viewer

This commit is contained in:
Megamouse 2022-04-08 00:46:53 +02:00
parent e53bbd668b
commit fb03a3bf67
2 changed files with 45 additions and 4 deletions

View File

@ -9,6 +9,7 @@
#include <QMenu>
#include <QFile>
#include <QFileDialog>
#include <QInputDialog>
#include <QTextStream>
#include <QHBoxLayout>
#include <QFontDatabase>
@ -57,19 +58,22 @@ log_viewer::log_viewer(std::shared_ptr<gui_settings> gui_settings)
void log_viewer::show_context_menu(const QPoint& pos)
{
QMenu menu;
QAction* clear = new QAction(tr("&Clear"));
QAction* open = new QAction(tr("&Open log file"));
QAction* clear = new QAction(tr("&Clear"));
QAction* open = new QAction(tr("&Open log file"));
QAction* filter = new QAction(tr("&Filter log"));
menu.addAction(open);
menu.addSeparator();
menu.addAction(filter);
menu.addSeparator();
menu.addAction(clear);
connect(clear, &QAction::triggered, [this]()
connect(clear, &QAction::triggered, this, [this]()
{
m_log_text->clear();
});
connect(open, &QAction::triggered, [this]()
connect(open, &QAction::triggered, this, [this]()
{
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select log file"), m_path_last, tr("Log files (*.log);;"));
if (file_path.isEmpty())
@ -78,6 +82,14 @@ void log_viewer::show_context_menu(const QPoint& pos)
show_log();
});
connect(filter, &QAction::triggered, this, [this]()
{
m_filter_term = QInputDialog::getText(this, tr("Filter log"), tr("Enter text"), QLineEdit::EchoMode::Normal, m_filter_term);
if (m_filter_term.isEmpty())
return;
filter_log();
});
const auto obj = qobject_cast<QPlainTextEdit*>(sender());
QPoint origin;
@ -121,6 +133,33 @@ void log_viewer::show_log() const
}
}
void log_viewer::filter_log()
{
if (m_filter_term.isEmpty())
{
return;
}
QString result;
QString text = m_log_text->toPlainText();
if (text.isEmpty())
{
return;
}
QTextStream stream(&text);
for (QString line = stream.readLine(); !line.isNull(); line = stream.readLine())
{
if (line.contains(m_filter_term))
{
result += line + "\n";
}
};
m_log_text->setPlainText(result);
}
bool log_viewer::is_valid_file(const QMimeData& md, bool save)
{
const QList<QUrl> urls = md.urls();

View File

@ -21,10 +21,12 @@ private Q_SLOTS:
void show_context_menu(const QPoint& pos);
private:
void filter_log();
bool is_valid_file(const QMimeData& md, bool save = false);
std::shared_ptr<gui_settings> m_gui_settings;
QString m_path_last;
QString m_filter_term;
QPlainTextEdit* m_log_text;
LogHighlighter* m_log_highlighter;
std::unique_ptr<find_dialog> m_find_dialog;