【问题标题】:WxWidgets C++: Run function that changes label's text every secondWxWidgets C++:运行每秒更改标签文本的函数
【发布时间】:2021-11-25 18:22:39
【问题描述】:

我想调用一个函数,在我的应用中每秒更改 label(!) 的文本。这是因为这些值不断变化。

这是我制作的一个函数:

void refreshStuff(wxStaticText* staticText)
{
    
    
    
    // No need for adding the pause in the question, it's self-explanatory
    while(1) {
       
        int info1 = 15;
        staticText->SetLabel("Current X: " + std::to_string(info1));

    }

    
}

这不起作用,因为我们阻塞了主线程。只要它是那么容易。值得庆幸的是,SO 存在;介意告诉我怎么做吗?

【问题讨论】:

标签: c++ wxwidgets


【解决方案1】:

在这里,您应该使用 wx 更多地使用 this->,特别是事件。

class Frame : public wxFrame {

private:

    wxTimer * timer;
    wxPanel * panel;
    wxBoxSizer * sizer;
    wxStaticText * label;

public:

    int lable_num = 0;
    const int interval = 500;

    Frame() : wxFrame(NULL, wxID_ANY, "Name"){
        this->sizer = new wxBoxSizer(wxVERTICAL);
        this->panel = new wxPanel(this, wxID_ANY);
        this->label = new wxStaticText(
            this->panel, wxID_ANY, "Current x: 0"
        );

        this->timer = new wxTimer(this);
        // The bind bust be on the instance parent
        // not the instance of the calle
        this->Bind(wxEVT_TIMER, &Frame::on_timer, this);
        (*this->timer).Start(interval);

        this->sizer->Add(this->panel, 0, wxEXPAND);
        this->SetSizer(sizer);
    }

    ~Frame(){
        (*this->timer).Stop();
    }

    void on_timer(wxTimerEvent& ev) {
        this->label->SetLabel(
            "Current X: " + std::to_string(++lable_num)
        );
    }    

};

【讨论】:

  • 使用更多this->有什么意义?为什么要专门将它与 wx 一起使用?
  • @LauriNurmi,我猜是因为他使用内联的东西...
  • 主要是因为 wx 为您管理小部件实例,我发现很难跟踪代码的中间(特别是如果您有一个很好的 espagueti)父级在哪里或者它是否位于内部班上。这不是必需的,但我认为在使用 wx 时这是一种很好的做法。
  • @Alex,使用 this 是 C++ 语法糖。只要你遵循一些编码标准,你就可以不使用它
  • 如果您愿意,可以使用this->,但您永远不需要使用它,因此使用“更多”的建议是错误的。顺便说一句,您也不需要手动调用wxTimer::Stop(),计时器无论如何都会在它被销毁时停止。但这也是无害的,就像使用this->一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多