我想打开一个主窗口,然后在运行时稍后添加一些按钮。在窗口中添加小部件
编辑:更新我的代码考虑到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”。
我的目标是立即全功能按钮,即使下一个按钮还没有创建。
我该如何达到我的目的?
是的,它使用“-std = C++ 11”进行编译。我正在调整我的代码到您的评论。谢谢。 –