【问题标题】:std::cout to QTextBrowserstd::cout 到 QTextBrowser
【发布时间】:2018-07-09 11:52:04
【问题描述】:

我有一个 C++ 项目,我将一个小日志文件写入 std::cout。在这个项目中,我有一个我创建的主对象和一个运行代码的函数。 简化版本如下所示:

int main(int argc, char *argv[])
{
   std::string pathToSettingsFile(argv[1]);
   MainObject m(pathToSettingsFile);
   m.run();
}

现在我已经为这个应用程序开发了一个 Qt GUI。 条件之一是,我不能在我的项目中使用任何 QT 库。 (QT 只允许在目前完全独立于项目的 GUI 中使用 - 基本上 GUI 只创建一个可由项目加载的 settingsFile)

我是否有可能将 std::cout 重定向到 QTextBrowser? 我想过简单地添加第二个输入参数,默认情况下是 std::cout,但如果需要它指向 QTextBrowser。像这样:

int main(int argc, char *argv[])
{
   std::string pathToSettingsFile(argv[1]);
   std::ostream &output = std::cout;
   MainObject m(pathToSettingsFile, output);
   m.run();
}

如果我想从 QT 启动它,我只需添加另一个 ostream。

// GUI CODE:
QTextBrowser *tb = new QTextBrowser();
std::ostream myOstream = somehow connect myOstream to tb; 
MainObject m(pathToSettingsFile, output);
m.run();

但我不知道我怎么能做到这一点,如果这甚至可能......这可能是这个问题的另一个非常简单的解决方案。

感谢您的反馈

【问题讨论】:

  • 既然有一个非常好的std::clog,为什么还要写日志到std::cout呢???
  • 我认为你不能那样做。使用方法print(std::string) 创建一个接口,并为每种情况提供适当的实现。

标签: c++ qt output cout


【解决方案1】:

std::ostream 的构造函数将std::streambuf 作为其参数。要将写入的字符重定向到std::cout,请实现自定义std::streambuf,例如

class TBBuf : public std::streambuf
{
private:
    QTextBrowser *tbOut;

protected:
    virtual int_type overflow(int_type c) {
        if (c != traits_type::eof() && tbOut) {
            tbOut->moveCursor(QTextCursor::End);
            tbOut->insertPlainText((QChar(c)));
            return c;
        }
        return traits_type::eof();
    }

    // By default, superclass::xsputn call overflow method,
    // but for performance reason, here we override xsputn
    virtual std::streamsize xsputn(const char * str, std::streamsize n) {
        if (tbOut && n > 0) {
            tbOut->moveCursor(QTextCursor::End);
            tbOut->insertPlainText(QString::fromLatin1(str, n));
        }

        return n;
    }

public:
    TBBuf(QTextBrowser *tb) : tbOut(tb) {}
};

那么std::cout 可以通过以下方式重定向到QTextBrowser

QTextBrowser *tb = new QTextBrowser();
TBBuf *buf = new TBBuf(tb);

std::streambuf *oldBuf = std::cout.rdbuf();
std::cout.rdbuf(buf);

std::string pathToSettingsFile(argv[1]);
MainObject m(pathToSettingsFile);
m.run();

std::cout.rdbuf(oldBuf);
//cleanup
//...

或通过构造std::ostream,例如

QTextBrowser *tb = new QTextBrowser();
TBBuf *buf = new TBBuf(tb);

std::ostream output(buf);
MainObject m(pathToSettingsFile, output);
m.run();

注意,在实现std::streambuf 的子类时,只需覆盖virtual int_type overflow(int_type c) 即可,但可能效率不高(慢)。

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 2011-07-08
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 2023-03-11
    • 2010-12-10
    相关资源
    最近更新 更多