当前位置:   article > 正文

Qt|Linux工作笔记-第二种方式读取Linux中top命令(直接读取,非重定向)_8622qt top

8622qt top

第一种方式的链接如下:

https://mp.csdn.net/postedit/84067805

第一种方式是重定向到文件,然后读取,

 

第二种方式不重定向到文件,直接读取!

利用QProcess的特点

运行截图如下:

源码如下:

widget.h

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3. #include <QWidget>
  4. QT_BEGIN_NAMESPACE
  5. class QProcess;
  6. QT_END_NAMESPACE
  7. namespace Ui {
  8. class Widget;
  9. }
  10. class Widget : public QWidget
  11. {
  12. Q_OBJECT
  13. public:
  14. explicit Widget(QWidget *parent = 0);
  15. ~Widget();
  16. protected:
  17. void callTopShell();
  18. void initListWidget();
  19. protected slots:
  20. void readProcess();
  21. void processFinished();
  22. private:
  23. Ui::Widget *ui;
  24. QProcess *m_topProcess;
  25. };
  26. #endif // WIDGET_H

widget.cpp

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3. #include <QProcess>
  4. #include <QEventLoop>
  5. #include <QTimer>
  6. #include <QDebug>
  7. Widget::Widget(QWidget *parent) :
  8. QWidget(parent),
  9. ui(new Ui::Widget)
  10. {
  11. ui->setupUi(this);
  12. m_topProcess = new QProcess;
  13. callTopShell();
  14. connect(m_topProcess, SIGNAL(readyRead()), this, SLOT(readProcess()));
  15. connect(m_topProcess, SIGNAL(finished(int,QProcess::ExitStatus)),this, SLOT(processFinished()));
  16. initListWidget();
  17. }
  18. Widget::~Widget()
  19. {
  20. delete ui;
  21. }
  22. void Widget::callTopShell()
  23. {
  24. QString cmdTop = "top -b -n 1";
  25. m_topProcess->start(cmdTop);
  26. }
  27. void Widget::processFinished(){
  28. qDebug()<< "process Finished";
  29. QEventLoop loop;
  30. QTimer::singleShot(0.2 * 1000, &loop, SLOT(quit()));
  31. loop.exec();
  32. initListWidget();
  33. callTopShell();
  34. }
  35. void Widget::initListWidget()
  36. {
  37. ui->textEdit->clear();
  38. }
  39. void Widget::readProcess()
  40. {
  41. qDebug()<< "readProcess called!";
  42. //qDebug()<< m_topProcess->readAll();
  43. ui->textEdit->insertPlainText(m_topProcess->readAll());
  44. }

main.cpp

  1. #include "widget.h"
  2. #include <QApplication>
  3. int main(int argc, char *argv[])
  4. {
  5. QApplication a(argc, argv);
  6. Widget w;
  7. w.show();
  8. return a.exec();
  9. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/70233
推荐阅读
相关标签
  

闽ICP备14008679号