【发布时间】:2014-07-11 08:27:06
【问题描述】:
我正在 C++ 中创建一个用于桌面用途的二维码解码器,并希望使用批处理文件在 Windows 上执行 zbar 以读取图像。
它将与 Qt 一起使用,我想知道是否可以将批处理文件的输出更改为出现在 textEdit 中,我已经将标准输出 std::cout 更改为出现在 textEdit 中,我认为这样就可以了。
如果没有办法让它直接出现,有没有办法从批处理文件中获取结果并将其带回我的 c++ 程序?
这是我在网上找到的用于测试更改 std::cout 的代码:
main.cpp:
#include "qr.h"
#include <QtGui/QApplication>
#include <QtGui>
#include "qdebugstream.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.connect(&app,SIGNAL(lastWindowClosed()),&app,SLOT(quit()));
//QR w;
//w.show();
QMainWindow* mainWindow = new QMainWindow();
QTextEdit* myTextEdit = new QTextEdit(mainWindow);
myTextEdit->setReadOnly(true);
QDebugStream qout(std::cout, myTextEdit);
std::clog<<"hello";
mainWindow->show();
std::cout << "TEST" << std::endl;
//system("D:\\QRCode\\JQR_Gen\\Debug\\runZbar.bat");
return app.exec();
}
qdebugstream.h:
#ifndef QDEBUGSTREAM_H
#define QDEBUGSTREAM_H
#include <iostream>
#include <streambuf>
#include <string>
#include "qtextedit.h"
class QDebugStream : public std::basic_streambuf<char>
{
public:
QDebugStream(std::ostream &stream, QTextEdit* text_edit) : m_stream(stream)
{
log_window = text_edit;
m_old_buf = stream.rdbuf();
stream.rdbuf(this);
}
~QDebugStream()
{
// output anything that is left
if (!m_string.empty())
log_window->append(m_string.c_str());
m_stream.rdbuf(m_old_buf);
}
protected:
virtual int_type overflow(int_type v)
{
if (v == '\n')
{
log_window->append(m_string.c_str());
m_string.erase(m_string.begin(), m_string.end());
}
else
m_string += v;
return v;
}
virtual std::streamsize xsputn(const char *p, std::streamsize n)
{
m_string.append(p, p + n);
int pos = 0;
while (pos != std::string::npos)
{
pos = m_string.find('\n');
if (pos != std::string::npos)
{
std::string tmp(m_string.begin(), m_string.begin() + pos);
log_window->append(tmp.c_str());
m_string.erase(m_string.begin(), m_string.begin() + pos + 1);
}
}
return n;
}
private:
std::ostream &m_stream;
std::streambuf *m_old_buf;
std::string m_string;
QTextEdit* log_window;
};
#endif
这里是批处理文件代码:
@set PATH=%PATH%;C:\Program Files (x86)\ZBar\bin
@cd D:\QRCode\JQR_Gen
@zbarimg "test.bmp"
任何帮助将不胜感激,希望以这种方式进行,因为它似乎比在 c++ 中正确使用 zbar 容易得多,因为我读到它在 Windows 上没有很好的功能。
提前致谢。
【问题讨论】:
-
您可以在不使用批处理文件的情况下使用 QProcess 运行 'zbarimg "test.bmp"',并使用 QProcess API 读取输出。
-
我正在关注此qt-project.org/doc/qt-5/QProcess.html,但我无法确定需要进入程序 QString atm 才能运行此命令,atm 我只是使用批处理文件,但你说可以直接完成吗?也感谢您之前的快速回复
标签: c++ qt batch-file cmd