2015-12-24 120 views
-1

我想打开一个主窗口,然后在运行时稍后添加一些按钮。在窗口中添加小部件

编辑:更新我的代码考虑到PRIME的答案(也许使问题更精确)

我写了这个:

'ex_qt.h'

#include<QHBoxLayout> 
#include<QMainWindow> 

class ButtonWindow : public QMainWindow 
{ 
    Q_OBJECT; 

    signals: 
     void need_button(); 
    private slots: 
     void start_loop(); 
     void do_bing(); 
     void create_button(); 
    private: 
     QVBoxLayout* v_layout; 
    public: 
     ButtonWindow(); 
}; 

和 'ex_qt.cpp'

#include <iostream> 
#include <string> 
#include <thread> 
#include <chrono> 
#include <QtGui> 
#include "ex_qt.h" 
void ButtonWindow::start_loop() 
{ 
    for (int i=0;i<10;i++) 
    { 
     std::chrono::milliseconds timespan(500); 
     std::this_thread::sleep_for(timespan); 
     emit need_button(); 
    } 
} 

void ButtonWindow::create_button() 
{ 
    std::cout<<"Creating a new button"<<std::endl; 
    QPushButton* button= new QPushButton("auto"); 
    v_layout->addWidget(button); 
    button->show(); 
} 

void ButtonWindow::do_bing() { std::cout<<"BING"<<std::endl; } 

ButtonWindow::ButtonWindow(): 
    QMainWindow() 
{ 
    QWidget* button_widget = new QWidget(this); 
    v_layout=new QVBoxLayout(); 

    QPushButton* button= new QPushButton("click here to begin"); 
    QPushButton* button2= new QPushButton("make bing"); 
    v_layout->addWidget(button); 
    v_layout->addWidget(button2); 

    button_widget->setLayout(v_layout); 

    connect(button,SIGNAL(clicked() ),this, SLOT(start_loop())); 
    connect(button2,SIGNAL(clicked() ),this, SLOT(do_bing())); 
    connect(this,SIGNAL(need_button() ),this, SLOT(create_button())); 
    setCentralWidget(button_widget); 
} 

int main(int argc, char *argv[]) 
{ 
    QApplication app(argc, argv); 
    ButtonWindow* bw=new ButtonWindow(); 
    bw->show(); 
    app.exec(); 
    return 42; 
} 

通过这段代码,当点击“click here to begnin”时,我看到主窗口放大10倍,但按钮只在最后看到。 “bing”按钮也是如此:如果在循环循环时单击bing按钮,则仅在循环结束时显示“BING”。

我的目标是立即全功能按钮,即使下一个按钮还没有创建。

我该如何达到我的目的?

回答

0

其实这个程序需要改进n个,

但刚刚开始:

删除您启动功能完全。 然后改变你的主要以:

int main(int argc, char *argv[]) 
{ 
     QApplication app(argc, argv); 
     MainWindows* mw=new MainWindows(); 
     mw->show(); 
     app.exec(); 
} 

这将确保你的窗口中正确启动和事件循环中运行。 除了在某个时间间隔后添加一个窗口之外,在MainWindow类中使用一个计时器对象,以便在该时间间隔之后它可以给出一个信号,插入该信号的插槽(newButton可以是该函数/插槽)小部件的布局。

除了你需要主窗口,从QMainWindow派生你的类,使用初始化列表来初始化你的变量。

你的程序在你的类声明中甚至可以用类似的东西编译吗?

QHBoxLayout* main_layout=new QHBoxLayout; 
+1

是的,它使用“-std = C++ 11”进行编译。我正在调整我的代码到您的评论。谢谢。 –

0

答案是processEvents函数。 只需添加

qApp->processEvents(); 

emit need_button(); 

,一切似乎很好地工作。

相关问题