如何将插槽添加到QWidget?

问题描述:

我有一个QMainWindow,它有一个QAction其信号triggered()连接到插槽about2()如何将插槽添加到QWidget?

... 
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()

我可以在哪里添加此插槽以使此代码正常工作?

+0

我是否需要添加一个额外的.h,并在.h中添加一个插槽? – eason

这是好的,运行良好,因为您使用的插槽位于正确的位置:在您的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()不为pWidget,这是一个QWidget存在。您正尝试将信号连接到不存在的插槽。

您的occQt类来定义这个插槽,和按钮的信号clicked()连接到您的插槽类

// 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())); 

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

private slots : 
    void make_a_box(); 

而在你的.cpp文件:

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); 
} 
+0

我的pWidget中没有插槽,请更改pWidget - > this。它运行! – eason