【问题标题】:How to add a slot to a QWidget?如何将插槽添加到 QWidget?
【发布时间】:2016-05-23 07:49:21
【问题描述】:

我有一个 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()

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

【问题讨论】:

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

标签: c++ qt signals-slots


【解决方案1】:

这没问题,运行良好,因为您使用的插槽位于正确的位置:在您的 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()));

pWidget 的插槽 make_a_box() 不存在,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);
}

【讨论】:

  • 我的 pWidget 中没有插槽,更改 pWidget -> 这个。它运行了!
猜你喜欢
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 2014-11-29
  • 2014-12-05
  • 1970-01-01
相关资源
最近更新 更多