【发布时间】:2016-07-11 22:26:33
【问题描述】:
在一个 GUI 应用程序中,我使用了很多按钮。这些按钮标记为pbxx,其中xx 是网格布局中按钮的行号和列号。按下按钮时,需要突出显示。今天我读到了 lambda 函数 Brian Poteat 和 Kuba Ober 并认为我会尝试在我的代码中实现它。
在我的 GuiDisplay 类(继承 QMainWindow 的类)中,我有一个函数叫做:
make_connections();
这将使我所有的按钮连接(所有信号都连接到单个插槽on_pushbutton_clicked()。我在这里添加了代码:
GuiDisplay 类
class GuiDisplay : public QMainWindow
{
Q_OBJECT
public:
explicit GuiDisplay(QWidget *parent = 0);
~GuiDisplay();
... Some more public functions ...
/**
* @brief Connects all custom signals and slots.
*/
void make_connections();
/**
* @brief Will highlight the provided pushbutton with provided rgb colour
*/
void highlight_pushbutton(QPushButton &pb, const int rgb[]);
private slots:
void on_pushbutton_clicked(const QString& label);
private:
Ui::GuiDisplay *ui;
};
GuiDisplay类的make_connections函数
void GuiDisplay::make_connections()
{
// Loop through all the pushbuttons and connect clicked signal to clicked slot
QString pb_label = "";
for(int i = 0; i < 8; ++i)
{
for(int j = 0; j < 8; ++j)
{
// Find the pushbutton
pb_label = "pb" + QString::number(i) + QString::number(j);
QPushButton* pb_ptr = this->findChild<QPushButton*>(pb_label);
//connect(pb_ptr, SIGNAL(clicked()), this, SLOT(on_pushbutton_clicked()));
connect(pb_ptr, &QPushButton::clicked, [this]{on_pushbutton_clicked(pb_label);});
}
}
}
连接时出现问题
connect(pb_ptr, &QPushButton::clicked, [this]{on_pushbutton_clicked(pb_label);});
构建给了我以下错误
'pb_label' is not captured
所以我认为可以,那么执行以下操作似乎并没有错:
connect(pb_ptr, &QPushButton::clicked, [this, &pb_label]{on_pushbutton_clicked(pb_label);});
构建时的错误消失了,但是每当执行此代码时,我的 GUI 应用程序就会意外崩溃。不知道为什么。这里有什么帮助吗?
【问题讨论】:
-
按值捕获
pb_label,即[this, pb_label] -
或者你可以使用
[=]