Qt实时获取指定进程占用内存(Demo)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_21107433/article/details/81456589

1.UI设计

这里写图片描述

2.Demo 代码

头文件

#ifndef USEDMEMDEMO_H
#define USEDMEMDEMO_H

#include <QtGui/QWidget>
#include "ui_usedMemDemo.h"

#include <QProcess>
#include <QTimer>
#include <QTime>

class usedMemDemo : public QWidget
{
    Q_OBJECT

public:
    usedMemDemo(QWidget *parent = 0, Qt::WFlags flags = 0);
    ~usedMemDemo();

public slots:

    ///设置所监控的程序进程号
    void setProcessPID(const QString& pidStr);
    ///设置刷新频率
    void setFreshFrequency(const QString& iFrequency);
    ///开始获取
    void startFresh();
    ///停止
    void stopFresh();
    ///获取内存
    void getUsedMem();

private:
    Ui::usedMemDemoClass ui;

    ///定时器
    QTimer *timer;
    ///监控的程序的PID
    int PIDNum;
};

#endif // USEDMEMDEMO_H

源文件

#include "usedMemDemo.h"

usedMemDemo::usedMemDemo(QWidget *parent, Qt::WFlags flags)
    : QWidget(parent, flags)
{
    ui.setupUi(this);

    PIDNum = -1;
    timer = new QTimer(this);

    connect(ui.lineEdit_processPID,SIGNAL(textChanged(const QString&)),this,SLOT(setProcessPID(const QString&)));
    connect(ui.lineEdit_freshFrequency,SIGNAL(textChanged(const QString&)),this,SLOT(setFreshFrequency(const QString&)));
    connect(ui.pushButton_start,SIGNAL(clicked()),this,SLOT(startFresh()));
    connect(ui.pushButton_stop,SIGNAL(clicked()),this,SLOT(stopFresh()));
    connect(timer,SIGNAL(timeout()),this,SLOT(getUsedMem()));
}

usedMemDemo::~usedMemDemo()
{
    delete timer;
}

void usedMemDemo::setProcessPID(const QString& pidStr)
{
    this->PIDNum = pidStr.toInt();
}

void usedMemDemo::setFreshFrequency(const QString& iFrequency)
{
    int i = iFrequency.toInt();
    this->timer->setInterval(1000/i);
}

void usedMemDemo::startFresh()
{
    this->timer->start();
}

void usedMemDemo::stopFresh()
{
    this->timer->stop();
}

void usedMemDemo::getUsedMem()
{
    if(this->PIDNum == -1)
        return;
    ///获取当前进程PID
    QProcess p;
    p.start("tasklist /FI \"PID EQ " + QString::number(PIDNum) + " \"");    
    p.waitForFinished();
    QString result = QString::fromLocal8Bit(p.readAllStandardOutput());
    p.close();
    //替换掉","
    result = result.replace(",","");
    //匹配 '数字+空格+K'部分。
    QRegExp rx("(\\d+)(\\s)(K)");
    //初始化结果
    QString usedMem("");
    if(rx.indexIn(result) != -1)
    {
        //匹配成功
        usedMem = rx.cap(0);
    }
    //截取K前面的字符串,转换为数字,供换算单位使用。
    usedMem = usedMem.left(usedMem.length() - 1);
    //换算为MB的单位
    result = QString::number(usedMem.toDouble()/1024,'g',4) + "M";
    //获取当前时间(毫秒)
    QString currentTime = (QTime::currentTime()).toString("hh:mm:ss.zzz");
    ui.textEdit->append(currentTime+"  Occupied memory:"+result);
}

3.测试

这里写图片描述

展开阅读全文

没有更多推荐了,返回首页