一、环境介绍
操作系统: ubuntu 18.04 64位 PC机
QT版本: 5.12
二、运行效果图
三、核心代码
mainwindow.cpp代码:
#include "widget.h" #include "ui_widget.h" #include <QProcess> #include <QDebug> #include <sys/sysinfo.h> #include <QTimer> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); QTimer::singleShot(1000, this, SLOT(GetSystemInfo())); } void Widget::GetSystemInfo(void) { /*1. 获取当前系统磁盘使用情况*/ /* * 格式: /dev/sda1 49G 38G 9.3G 81% / */ QProcess process; process.start("df -h"); process.waitForFinished(); QByteArray output = process.readAllStandardOutput(); QString str_output = output; str_output=str_output.mid(str_output.indexOf("/dev/sda1")); //得到: /dev/sda1 49G 38G 9.3G 81% str_output=str_output.section('/',0,2); str_output=str_output.section(' ',1); //将多个空格换成单个空格 str_output=str_output.replace(QRegExp("[\\s]+"), " "); QString text; text="磁盘总容量: "+str_output.section(' ',1,1)+"\n"; text+="已用: "+str_output.section(' ',2,2)+"\n"; text+="可用: "+str_output.section(' ',3,3); //获取百分比 ui->progressBar_rom->setValue(str_output.section(' ',4,4).section('%',0,0).toInt()); ui->label_ROM->setText(text); /*2. 获取当前系统内存使用情况*/ struct sysinfo s_info; if(sysinfo(&s_info)==0) { text=tr("总内存: %1 KB\n").arg(s_info.totalram/1024); text+=tr("未使用内存: %1 KB\n").arg(s_info.freeram/1024); text+=tr("交换区总内存: %1 KB\n").arg(s_info.totalswap/1024); text+=tr("交换区未使用内存: %1 KB\n").arg(s_info.freeswap/1024); text+=tr("系统运行时间: %1s").arg(s_info.uptime); ui->label_RAM->setText(text); } QTimer::singleShot(1000, this, SLOT(GetSystemInfo())); } Widget::~Widget() { delete ui; }
mainwindow.h代码:
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACE class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr); ~Widget(); private slots: void GetSystemInfo(void); private: Ui::Widget *ui; }; #endif // WIDGET_H