Put controls in the qt table

1. Background

It is to put controls in the table, or to dynamically generate controls, just like Excel, which is easy to operate, and this is also a manifestation of the powerful interface. The previous interfaces are all text boxes and the like. Obviously, the operation is relatively simple. If the logic is complex , it is more troublesome to deal with

2. Examples

2.1. Interface situation:

insert image description here

2.2, the situation of the header file

#ifndef DYNAMICCTRLDIALOG_H
#define DYNAMICCTRLDIALOG_H

#include <QDialog>
#include <QTableWidget>

namespace Ui {
    
    
class DynamicCTRLDialog;
}

class DynamicCTRLDialog : public QDialog
{
    
    
    Q_OBJECT

public:
    explicit DynamicCTRLDialog(QWidget *parent = 0);
    ~DynamicCTRLDialog();
    void init();
private slots:
    void changTextListPath(QString str);
private:
    Ui::DynamicCTRLDialog *ui;
    QTableWidget *m_tableWidget;
};

#endif // DYNAMICCTRLDIALOG_H

2.2. Generate controls on the parent window

    m_tableWidget = ui->tableWidget;
    m_tableWidget->setRowCount(1);

    QTableWidgetItem *item = new QTableWidgetItem();
    m_tableWidget->setItem(0, 0, item);
    item->setText(QString::fromStdString("小明"));
    item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    item = new QTableWidgetItem();
    m_tableWidget->setItem(0, 1, item);
    //1/new一个控件,并且指定其父窗口
    QComboBox *combobox_Args=new QComboBox(m_tableWidget);
    QStringList combobox_subArgs_list;
    combobox_subArgs_list.append("1班");
    combobox_subArgs_list.append("2班");
    combobox_Args->addItems(combobox_subArgs_list);
    combobox_Args->setCurrentIndex(1);

2.2, Specify the location of the table

 //2/指定位置
    m_tableWidget->setCellWidget(0,1,combobox_Args);

2.3, specify the event of the control

connect(combobox_Args,SIGNAL(currentIndexChanged(QString)),this,SLOT(changTextListPath(QString)));

void DynamicCTRLDialog::changTextListPath(QString str)
{
    
    
    qDebug()<<str;
}

2.4. Effects

insert image description here

3. Summary

Generally speaking, the implementation is quite simple. The key step is to generate controls on the parent window, generate controls on the parent window, and reflect them on the interface, that is, the controls become part of the parent window, and then put them in the specified position.
When creating a control, you can specify to dock on a certain parent window. At this time, the control will be bound inside its parent window as a child window, and will
move, hide, display and close with the parent window; otherwise, the control will act as an independent window. The window is displayed on the screen and is free from other windows

insert image description here

Guess you like

Origin blog.csdn.net/maokexu123/article/details/126491080