如何将标准输出消息重定向到FLTK的Fl_Multiline_Output?

时间:2019-11-15 16:00:05

标签: c++ fltk

Fl_Multiline_Output* m_pLogOutput;

m_pLogOutput = new Fl_Multiline_Output(20, 330, 570, 530, "Log Output:");
m_pLogOutput->align(FL_ALIGN_TOP_LEFT);

我想重定向任何打印到标准输出的消息(例如std :: cout <<“ Hello world”)以显示在此m_pLogOutput上。有可能吗?

1 个答案:

答案 0 :(得分:0)

类似的事情-本示例使用TextDisplay代替MultiLineOutput。 TextDisplay有滚动条:MultilineOutput没有。这是用FLTK2写的,调用类似于FLTK1,但没有FL_,并且单词之间带有下划线。

它定义了一个名为ConOut的类。请注意,您不能

#include <iostream>

因为重新定义了cout。

#include <fltk/run.h>
#include <fltk/ValueInput.h> // necessary for bug in mingw32?
#include <fltk/Window.h>
#include <fltk/Button.h>
#include <fltk/TextDisplay.h>
#include <sstream>

using namespace fltk;

class ConOut: public std::ostringstream
{
public:
    ConOut& operator << (std::ostream&(*f)(std::ostream&))
    {
        if (f == std::endl)
        {
            *this << "\n";
            std::string cumulative = control->text() + str();
            control->text(cumulative.c_str());
            str("");
        }
        else
        {
            // Don't worry about the warning
            *this << f;
        }
        return *this;
    }

    void SetWidget(TextDisplay* in_control)
    {
        control = in_control;
    }

    TextDisplay* control;

    template <typename T>
    inline ConOut& operator << (const T& t)
    {
        (*(std::ostringstream*) this) << t;
        return *this;
    }
};

ConOut cout;

void cb_cauli(Widget*, void*)
{
    cout << "Cauliflower" << std::endl;
}

void cb_brocolli(Widget*, void*)
{
    cout << "Brocolli" << std::endl;
}

void cb_cabbage(Widget*, void*)
{
    cout << "Cabbage" << std::endl;
}

int main(int argc, char **argv)
{
    int btnw = 100, btnh = 30, bdr = 10;
    int dlgw = bdr * 4 + 3 * btnw, dlgh = 200 + btnh + 3 * bdr, x, y, w, h;
    Window * window = new Window(dlgw, dlgh);
    window->begin();

    // Create the multiline output
    x = bdr;
    y = bdr;
    w = dlgw - 2 * bdr;
    h = 200;
    TextDisplay* text2 = new TextDisplay(x, y, w, h,"");
    text2->clear_flag(fltk::ALIGN_MASK);
    text2->set_flag(fltk::ALIGN_BOTTOM);
    window->resizable(text2);

    // Create the buttons which use cout
    y += h + bdr;
    w = btnw; h = btnh;
    Button* cauli = new Button(x, y, w, h, "Cauliflower");
    cauli->callback(cb_cauli);
    x += w + bdr;
    Button* brocolli = new Button(x, y, w, h, "Brocolli");
    brocolli->callback(cb_brocolli);
    x += w + bdr;
    Button* cabbage = new Button(x, y, w, h, "Cabbage");
    cabbage->callback(cb_cabbage);

    // Set the widget for cout
    cout.SetWidget(text2);

    window->end();
    window->show(argc,argv);
    return fltk::run();
}