【问题标题】:Qt connect multiple signal with slot using functionQt使用功能将多个信号与插槽连接
【发布时间】:2021-09-03 09:16:30
【问题描述】:

如果我点击一个按钮,我想设置字体颜色和背景颜色。

我刚刚将这两个函数添加到mainwindow.h文件中

public:
    void createGrid();

private slots:
    void clickCell(int row, int col);

mainwindow.cpp

QVector<QVector<QPushButton*>> buttons(10);

void MainWindow::createGrid() {
    QFrame *frame = new QFrame(this);
    QGridLayout *layout = new QGridLayout(frame);

    layout->setMargin(0);
    layout->setSpacing(0);

    for(int i = 0; i < 10; ++i){
        buttons[i].resize(10);

        for(int j = 0; j < 10; ++j){
            QPushButton *button = new QPushButton("0");

            button->setMinimumSize(50,50);
            button->setMaximumSize(50,50);

            connect(button,SIGNAL(released()),this,SLOT(clickCell(i,j)));

            layout->addWidget(button,i,j);

            buttons[i][j] = button;
        }

    }

    setCentralWidget(frame);
}

void MainWindow::clickCell(int row, int col) {
    buttons[row][col]->setStyleSheet("background-color: grey; color: red");
}

当我运行我的代码时,我得到了大约 100 次以下输出:

QObject::connect: No such slot MainWindow::clickCell(i,j) in ..\untitled\mainwindow.cpp:41
QObject::connect:  (receiver name: 'MainWindow')

【问题讨论】:

标签: c++ qt signals-slots


【解决方案1】:

根据评论:使用新的信号/槽语法来调用 lambda 作为槽。所以你的connect 电话应该类似于(未经测试)......

connect(button, &QPushButton::released, this,
        [=, this]
        {
            clickCell(i, j);
        });

【讨论】:

    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2015-03-14
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多