我需要创建一个能够运行命令行批处理和命令的QT GUI应用程序。例如,ping,tcpdump等......
我会想象它是这样的: 带有QTableView的标准图形窗口,一些复选框等......带有组件实例QPlainTextEdit。该组件(QPlainTextEdit)将充当命令行,允许输入命令并捕获其输出。
这样的事情可能吗?该怎么做?
答案 0 :(得分:1)
您可以将QProcess用于您的目的..
QProcess cmd;
cmd.start("cmd");
此处有更多细节..
答案 1 :(得分:1)
主要思想是使用QProcess
来运行命令。请参阅以下代码进行演示。
QProcess process;
// If "command" is not in your path,
// use the corresponding relative or absolute path
process.start("command", QStringList()
<< QString("-arg1")
<< QString("arg2")
<< QString("-arg3")
<< QString("arg4"));
// Wait for it to start
if(!process.waitForStarted())
return 0;
bool retval = false;
QByteArray buffer;
while ((retval = process.waitForFinished()));
buffer.append(process.readAll());
if (!retval) {
yourPlainTextEdit.appendPlainText(process.errorString());
} else {
yourPlainTextEdit.appendPlainText(buffer);
}
MyClass::MyClass(QQProcess *process, QObject *parent)
: QObject(parent)
, m_process(process)
{
connect(m_process, SIGNAL(readyRead()), SLOT(handleReadyRead()));
connect(m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(handleError(QProcess::ProcessError)));
connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));
m_timer.start(5000);
}
MyClass::~MyClass()
{
}
void MyClass::handleReadyRead()
{
m_readData.append(m_process->readAll());
if (!m_timer.isActive())
m_timer.start(5000);
}
void MyClass::handleTimeout()
{
if (m_readData.isEmpty()) {
yourPlainTextEdit.appendPlainText("No data was currently available for reading from gnuplot");
} else {
yourPlainTextEdit.appendPlainText("Process successfully run");
}
}
void GnuPlotReader::handleError(QProcess::ProcessError processError)
{
if (processError == QProcess::ReadError) {
appendPlainTextEdit.appendPlainText("An I/O error occurred while reading the data, error: %1").arg(m_process->errorString()));
yourPlainTextEdit.appendPlainText(m_readData);
}
}
免责声明:这是完全未经测试的代码,因此它可能存在编译器和运行时问题,但这应该可以很好地掌握它,而不用多说。