c++ - Qt 信号和槽传递数据

标签 c++ qt signals

我是 c++ 和 qt 的新手。我不确定我是否使用了正确的术语来描述我想要实现的目标。但就这样吧。

当用户按下按钮时,我的应用程序在网格布局中生成和删除小部件。成功地做到了这一点。但是,当用户使用生成的小部件时,我希望小部件相互交互

QList<QLineEdit*> m_ptrLEPathList;
QList<QPushButton*> m_ptrPBList;

qint8 m_noFields;

void MainWindow::on_pbIncFields_clicked()
{
    //create widgets and place on a new row in a gridLayout
    QLineEdit *lineEditPath = new QLineEdit(this);
    QPushButton *pushButton = new QPushButton(this);

    //storing pointers in lists to be able to delete them later.
    m_ptrLEPathList.append(lineEditPath);
    m_ptrPBList.append(pushButton);

    ui->gridLayout->addWidget(m_ptrLEPathList.last(),m_noFields,0);
    ui->gridLayout->addWidget(m_ptrPBList.last(),m_noFields,1);

    connect(m_ptrPBList.last(), SIGNAL(clicked(bool), this, SLOT(on_addPath()));
    m_noFields++;
}

void MainWindow::on_pbDecFields()
{
    //delete last spawned widgets
}

void MainWindow::on_addPath()
{
    QFileDialog getPath();
    getPath.exec();

    //somehow set the text of the line edit spawned on the same row as the pushbutton

}

因此,当我按下任何生成的按钮时,我的插槽就会被执行,但我不知道如何将文件对话框中的数据存储在相关的 lineEdit 中

我尝试做的事情的基本想法是否正确,或者是否有任何其他解决方案来实现我正在寻找的功能?

最佳答案

on_addPath 插槽中,您可以使用 QObject::sender 方法来获取单击的按钮,并且假设 m_ptrLEPathListm_ptrPBList 列表是相等的,可以很容易的得到对应的QLineEdit:

void MainWindow::on_addPath()
{
    QFileDialog dialog;
    if (!dialog.exec())
    {
        return;
    }

    QStringList fileNames = dialog.selectedFiles();
    if (fileNames.isEmpty())
    {
        return;
    }

    QPushButton *btn = qobject_cast<QPushButton*>(sender());
    if (!btn)
    {
        return;
    }

    Q_ASSERT(m_ptrPBList.size() == m_ptrLEPathList.size());

    int index = m_ptrPBList.indexOf(btn);
    if (index == -1)
    {
        return;
    }

    QLineEdit *edit = m_ptrLEPathList.at(index);
    edit->setText(fileNames.first());
}

关于c++ - Qt 信号和槽传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125161/

相关文章:

c++ - 如何仅使用对中的第一个元素在集合中找到对?

c++ - 使用 setjmp longjmp 时出现段错误

haskell - 如何在haskell中处理SIGWINCH?

c++ - 如何在不修改基类的情况下使用 Boost::Python 向导出类添加方法?

c++ - 'list::list' 命名构造函数,而不是类型

c++ - Qt开发lib和跨平台截屏是真的吗?

linux - 当使用 -platform eglfs 运行 Qt5 应用程序时,i.MX6 上的 "EGL Error : could not create the EGL surface: error 0x300b"

qt - 如何在 QML 中将项目拖动到 ListView 之外

c - 我想连续从COM端口接收数据,同时想写入文件

c++ - 在类中使用未声明的标识符