C++ 动态添加小部件
我想打开一个主窗口,然后在运行时添加一些按钮 编辑:我更新代码以考虑PRIME的答案(可能会使问题更精确) 我写道: “ex_qt.h”C++ 动态添加小部件,c++,qt,C++,Qt,我想打开一个主窗口,然后在运行时添加一些按钮 编辑:我更新代码以考虑PRIME的答案(可能会使问题更精确) 我写道: “ex_qt.h” #include<QHBoxLayout> #include<QMainWindow> class ButtonWindow : public QMainWindow { Q_OBJECT; signals: void need_button(); private slots:
#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();
};
#包括
#包括
类按钮窗口:公共QMainWindow
{
Q_对象;
信号:
void need_按钮();
专用插槽:
void start_loop();
void do_bing();
void create_按钮();
私人:
QVBoxLayout*v_布局;
公众:
按钮窗口();
};
和“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;
}
#包括
#包括
#包括
#包括
#包括
#包括“ex_qt.h”
void按钮窗口::开始循环()
{
对于(int i=0;i实际上,该程序需要n个改进
但首先:
完全删除您启动的功能。
然后将主菜单更改为:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindows* mw=new MainWindows();
mw->show();
app.exec();
}
这将确保窗口正确启动并在事件循环中运行。
除此之外,要在某个时间间隔后添加窗口,请在MainWindow类中使用timer对象,以便在该时间间隔后,它可以向该信号的插槽(newButton
可以是该函数/插槽)发送信号,您可以将小部件添加到布局中
此外,因为您需要主窗口,所以从QMainWindow派生类,使用初始值设定项列表来初始化变量
您的程序是否在类声明中使用类似的内容进行编译
QHBoxLayout* main_layout=new QHBoxLayout;
答案是函数。
加上
之后
emit need_button();
一切似乎都很好。是的,它确实使用“-std=c++11”编译。我正在根据您的评论调整我的代码。谢谢。
emit need_button();