如何在QWidget中添加一个插槽?

时间:2016-05-23 07:49:22

标签: c++ qt signals-slots

我有一个QMainWindow,其QAction信号triggered()已连接到广告位about2()

...
connect(mAboutAction2, SIGNAL(triggered()), this, SLOT(about2()));
...


void occQt::about2()  //UI
{
    QWidget* pWidget = new QWidget;
    QPushButton* okbtn = new QPushButton(tr("ok"));
    QPushButton* cancelbtn = new QPushButton(tr("cancel"));
    btnlayout->addWidget(okbtn);
    btnlayout->addWidget(cancelbtn);
    dlglayout->setMargin(50);
    dlglayout->addLayout(gridlayout);
    dlglayout->addStretch(40);
    dlglayout->addLayout(btnlayout);
    pWidget->setLayout(dlglayout);
    pWidget->setWindowTitle(tr("Make a Box by custom."));
    pWidget->show();
    connect(okbtn, SIGNAL(clicked()), pWidget, SLOT(make_a_box()));
    connect(cancelbtn, SIGNAL(clicked()), pWidget, SLOT(close()));
}

void occQt::make_a_box()
{
    TopoDS_Shape aTopoBox = BRepPrimAPI_MakeBox(3.0, 4.0, 95.0).Shape();
    Handle_AIS_Shape anAisBox = new AIS_Shape(aTopoBox);

    anAisBox->SetColor(Quantity_NOC_AZURE);

    mContext->Display(anAisBox);
}

当我运行插槽about2()时,UI会打开。我点击cancelbtn时可以关闭它,但我无法进入广告位make_a_box()

我可以在哪里添加此广告位以使此代码正常工作?

1 个答案:

答案 0 :(得分:4)

这没关系并且运行正常,因为您使用的插槽位于正确的位置:在occQt类中。

// You connect the signal FROM the action TO "this", i.e. your class
connect(mAboutAction2, SIGNAL(triggered()), this, SLOT(about2()));

void occQt::about2()  //UI
{

    QWidget* pWidget = new QWidget;
    QPushButton* okbtn = new QPushButton(tr("ok"));
    QPushButton* cancelbtn = new QPushButton(tr("cancel"));
    btnlayout->addWidget(okbtn);
    btnlayout->addWidget(cancelbtn);
    dlglayout->setMargin(50);
    dlglayout->addLayout(gridlayout);
    dlglayout->addStretch(40);
    dlglayout->addLayout(btnlayout);
    pWidget->setLayout(dlglayout);
    pWidget->setWindowTitle(tr("Make a Box by custom."));
    pWidget->show();

现在,这不行:

 // You connect the signal FROM the button to pWidget, which doesn't have a slot make_a_box()
 connect(okbtn, SIGNAL(clicked()), pWidget, SLOT(make_a_box()));

make_a_box()的{​​{1}}广告位不存在pWidget。您正在尝试将信号连接到不存在的插槽。

您必须在QWidget课程中定义此插槽,并将按钮的信号occQt连接到班级中的插槽

clicked()

在您的.h文件中,您将拥有:

// Now, you connect the signal FROM the button to "this", which is your class and has a slot make_a_box()
connect(okbtn, SIGNAL(clicked()), this, SLOT(make_a_box()));

在你的.cpp文件中:

private slots : 
    void make_a_box();