gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:44:55 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com