qt 获取动态生成的qlineedit值

1.头文件代码

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void addbutton_Clicked();
    void deletebutton_Clicked();
    void lineedit_textChanged(QString text);
private:
    Ui::MainWindow *ui;

public:
    QVBoxLayout *middlelayout;
    QList qlist;
    std::vector users;
};

#endif // MAINWINDOW_H

二.源文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //ui->setupUi(this);
    QWidget *window = new QWidget(this);
    QVBoxLayout *mainlayout = new QVBoxLayout;
    middlelayout = new QVBoxLayout;
    QHBoxLayout *buttonlayout = new QHBoxLayout;
    QPushButton *addbutton = new QPushButton;
    QPushButton *deletebutton = new QPushButton;

    addbutton->setText("ADD");
    deletebutton->setText("Delete");

    buttonlayout->addWidget(addbutton);
    buttonlayout->addWidget(deletebutton);
    buttonlayout->setAlignment(Qt::AlignTop);

    mainlayout->addLayout(buttonlayout);
    mainlayout->addLayout(middlelayout);

    window->setLayout(mainlayout);
    setCentralWidget(window);

    connect(addbutton, SIGNAL(clicked()), SLOT(addbutton_Clicked()));
    connect(deletebutton, SIGNAL(clicked()), SLOT(deletebutton_Clicked()));
}

MainWindow::~MainWindow()
{
    //delete ui;
}

void MainWindow::addbutton_Clicked()
{
    QLineEdit *lineedit = new QLineEdit;
    qlist.push_back(lineedit);
    middlelayout->addWidget(lineedit);
    lineedit->setObjectName("lineedit"+QString::number(qlist.count()));

    users.resize(qlist.count());
    connect(lineedit, SIGNAL(textChanged(QString)), SLOT(lineedit_textChanged(QString)));
}

void MainWindow::deletebutton_Clicked()
{
    QWidget *child;
    if (!middlelayout->isEmpty())
    {
        if ((child = middlelayout->takeAt(qlist.count()-1)->widget()) != 0)
        {
            delete child;
            qlist.removeLast();
        }
    }
}

void MainWindow::lineedit_textChanged(QString text)
{
    QObject *obj = QObject::sender();
    QString senderobjName = obj->objectName();
    int isTextchanged = senderobjName.indexOf("lineedit") != -1;
    if (isTextchanged)
    {
        QStringList list = senderobjName.split("lineedit");
        unsigned int index = list[1].toInt();
        users[index] = text;
        qDebug() << users[index];
    }
}

三.效果

qt 获取动态生成的qlineedit值_第1张图片
关注问我技术公众号,加小问,拉您入技术交流群:
qt 获取动态生成的qlineedit值_第2张图片

你可能感兴趣的:(C++)