Table of Contents
1. Introduction" >1. Introduction
For example, by double-clicking a cell, you can modify the original content. If you want to prohibit the user from doing this and make the table read-only for the user, you can do this: " >1. Disable editing of the tableBy default, in the table The characters can be changed. For example, by double-clicking a cell, you can modify the original content. If you want to prohibit the user from doing this and make the table read-only for the user, you can do this:
3、QTableWidget美化" >3、QTableWidget美化
Home Backend Development PHP Tutorial Code implementation to create QT tables

Code implementation to create QT tables

Mar 30, 2018 pm 01:30 PM

This article mainly shares a code to implement the request method for making QT tables. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.

1. Introduction

QTableWidget is a control commonly used in QT dialog box design to display data tables. QTableWidget cell data is the QTableWidgetItem object. To achieve this, the entire table needs to be constructed using cell-by-cell objects QTableWidgetItem.


##2. Detailed explanation

1. Code

(1)table.h

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    #ifndef TABLE_H 

    #define TABLE_H 

    #include <QtGui> 

       

    class Table : public QTableWidget 

        Q_OBJECT 

    public

        Table(QWidget *parent = 0); 

        ~Table(); 

        void setColumnValue(const int &columnSum, const QStringList &header);   //set header value 

        void setHeaderWidth(const int &index, const int &width);    //set header and column widhth for each index 

        void setHeaderHeight(const int &height);                    //set header height 

       

        void addRowValue(const int &height, const QStringList &value, const QIcon &fileIcon); 

        void setRowH(const int &index, const int &height); 

        void setItemFixed(bool flag); 

        bool getSelectedRow(QList<int> &rowList); 

           

    protected

        void contextMenuEvent(QContextMenuEvent *event); 

        QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers); 

        void keyPressEvent(QKeyEvent *event); 

       

    private

        void createActions(); 

           

    private slots: 

        void slotItemEntered(QTableWidgetItem *item); 

        void slotActionRename(); 

        void slotItemSelectionChanged(); 

           

    private

        int tableWidth; 

        int tableHeight; 

        QList<int>rowHeghtList; 

        QList<int>rowWidthList; 

           

        QMenu *popMenu; 

        QAction *actionName; 

        QAction *actionSize; 

        QAction *actionType; 

        QAction *actionDate; 

        QAction *actionOpen; 

        QAction *actionDownload; 

        QAction *actionFlush; 

        QAction *actionDelete; 

        QAction *actionRename; 

        QAction *actionCreateFolder; 

        QTableWidgetItem *rightClickedItem; 

        QMap<QTableWidgetItem *, QString>fileMap; 

        bool dupFlag; 

    }; 

       

    // custom item delegate class 

    class NoFocusDelegate : public QStyledItemDelegate 

    protected

        void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const

    }; 

    #endif // TABLE_H

    Copy after login

(2)table.cpp


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

    76

    77

    78

    79

    80

    81

    82

    83

    84

    85

    86

    87

    88

    89

    90

    91

    92

    93

    94

    95

    96

    97

    98

    99

    100

    101

    102

    103

    104

    105

    106

    107

    108

    109

    110

    111

    112

    113

    114

    115

    116

    117

    118

    119

    120

    121

    122

    123

    124

    125

    126

    127

    128

    129

    130

    131

    132

    133

    134

    135

    136

    137

    138

    139

    140

    141

    142

    143

    144

    145

    146

    147

    148

    149

    150

    151

    152

    153

    154

    155

    156

    157

    158

    159

    160

    161

    162

    163

    164

    165

    166

    167

    168

    169

    170

    171

    172

    173

    174

    175

    176

    177

    178

    179

    180

    181

    182

    183

    184

    185

    186

    187

    188

    189

    190

    191

    192

    193

    194

    195

    196

    197

    198

    199

    200

    201

    202

    203

    204

    205

    206

    207

    208

    209

    210

    211

    212

    213

    214

    215

    216

    217

    218

    219

    220

    221

    222

    223

    224

    225

    226

    227

    228

    229

    230

    231

    232

    233

    234

    235

    236

    237

    238

    239

    240

    241

    242

    243

    244

    245

    246

    247

    248

    249

    250

    251

    252

    253

    254

    255

    256

    257

    258

    259

    260

    261

    262

    263

    264

    265

    266

    267

    268

    269

    270

    271

    272

    273

    274

    275

    276

    277

    278

    279

    280

    281

    282

    283

    284

    285

    286

    287

    288

    289

    290

    291

    292

    293

    294

    295

    296

    297

    298

    299

    300

    301

    302

    303

    #include "table.h" 

       

    Table::Table(QWidget *parent) 

        : QTableWidget(parent) 

        , rightClickedItem(NULL) 

        , dupFlag(false) 

        rowHeghtList.clear(); 

        rowWidthList.clear(); 

        fileMap.clear(); 

        this->setMouseTracking(true); 

        //setWindowTitle(tr("table")); 

        horizontalHeader()->setDefaultSectionSize(100); 

        verticalHeader()->setDefaultSectionSize(30);    //设置默认行高 

        tableWidth = 100; 

        tableHeight = 30; 

        horizontalHeader()->setClickable(false);    //设置表头不可点击(默认点击后进行排序 

       

        QFont font = horizontalHeader()->font();    //设置表头字体加粗 

        font.setBold(true); 

        horizontalHeader()->setFont(font); 

        horizontalHeader()->setStretchLastSection(true);    //设置充满表宽度 

        horizontalHeader()->setMovable(false);              //表头左右互换 

        //verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); 

       

        setFrameShape(QFrame::NoFrame);      //设置无边框 

        //setShowGrid(false);                //设置不显示格子线 

        verticalHeader()->setVisible(false); //设置垂直头不可见 

        setSelectionMode(QAbstractItemView::ExtendedSelection);  //可多选(Ctrl、Shift、  Ctrl+A都可以) 

        setSelectionBehavior(QAbstractItemView::SelectRows);  //设置选择行为时每次选择一行 

        setEditTriggers(QAbstractItemView::NoEditTriggers); //设置不可编辑 

       

        setStyleSheet("selection-background-color:lightblue;");  //设置选中背景色 

        //horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); //设置表头背景色 

        //setStyleSheet("background: rgb(56,56,56);alternate-background-color:rgb(48,51,55);selection-background-color:qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(56,56,56),stop:1 rgb(76,76,76));"); //设置选中背景色 

        horizontalHeader()->setStyleSheet("QHeaderView::section{background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(134, 245, 99, 255),stop:0.5 rgba(134, 148, 99, 255),stop:1 rgba(115, 87, 128, 255));color:rgb(25, 70, 100);padding-left: 1px;border: 1px solid #FFFF00;}"); //设置表头背景色 

        setAlternatingRowColors(true); 

       

        //setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 

        //setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 

        //设置水平、垂直滚动条样式 

        horizontalScrollBar()->setStyleSheet("QScrollBar{background:transparent; height:12px;}" 

                                             "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}" 

                                             "QScrollBar::handle:hover{background:gray;}" 

                                             "QScrollBar::sub-line{background:transparent;}" 

                                             "QScrollBar::add-line{background:transparent;}"); 

       

        verticalScrollBar()->setStyleSheet("QScrollBar{background:transparent; width:12px;}" 

                                           "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}" 

                                           "QScrollBar::handle:hover{background:gray;}" 

                                           "QScrollBar::sub-line{background:transparent;}" 

                                           "QScrollBar::add-line{background:transparent;}"); 

       

        // set the item delegate to your table widget 

        setItemDelegate(new NoFocusDelegate());             //虚线边框去除 

        //setFocusPolicy(Qt::NoFocus);   //去除选中虚线框 

        horizontalHeader()->setHighlightSections(false);    //点击表时不对表头行光亮(获取焦点) 

       

        createActions(); 

        setItemFixed(false); 

        connect(this, SIGNAL(itemEntered(QTableWidgetItem*)), this , SLOT(slotItemEntered(QTableWidgetItem*))); 

        connect(this, SIGNAL(itemSelectionChanged()), this , SLOT(slotItemSelectionChanged())); 

        //this->resize(600, 600); 

       

    Table::~Table() 

       

       

    void Table::setColumnValue(const int &columnSum, const QStringList &header) 

        setColumnCount(columnSum);                //设置列数 

        this->setHorizontalHeaderLabels(header);  //设置列的标签 

       

    void Table::setHeaderWidth(const int &index, const int &width) 

        horizontalHeader()->resizeSection(index,width); 

        if (rowWidthList.count() <= index + 1) { 

          rowWidthList.append(width); 

        

        else

          rowWidthList[index+1] = width; 

        

        tableWidth = 0; 

        for(int index = 0; index < rowWidthList.count(); index++) 

           tableWidth += rowWidthList.at(index); 

        resize(tableWidth, tableHeight); 

       

    void Table::setHeaderHeight(const int &height) 

        horizontalHeader()->setFixedHeight(height);        //设置表头的高度 

        if (rowHeghtList.isEmpty()) { 

          rowHeghtList.append(height); 

        

        else

          rowHeghtList[0] = height; 

        

        tableHeight = 0; 

        for(int index = 0; index < rowHeghtList.count(); index++) 

           tableHeight += rowHeghtList.at(index); 

        resize(tableWidth, tableHeight); 

       

    void Table::addRowValue(const int &height, const QStringList &value, const QIcon &fileIcon) 

        int row_count = rowCount();    //获取表单行数 

        insertRow(row_count);          //插入新行 

        setRowHeight(row_count, height); 

        for (int index = 0; index < columnCount(); index++) { 

            QTableWidgetItem *item = new QTableWidgetItem; 

            if (index == 0) { 

                item->setIcon(fileIcon); 

                item->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); 

                fileMap.insert(item, value.at(index)); 

            

            else

                item->setTextAlignment(Qt::AlignCenter); 

            

            item->setText(value.at(index)); 

            setItem(row_count, index, item); 

        

        rowHeghtList.append(height); 

        tableHeight += height;  

        resize(tableWidth, tableHeight); 

       

       

    void NoFocusDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const 

        QStyleOptionViewItem itemOption(option); 

        if (itemOption.state & QStyle::State_HasFocus) 

            itemOption.state = itemOption.state ^ QStyle::State_HasFocus; 

        QStyledItemDelegate::paint(painter, itemOption, index); 

       

    void Table::setRowH(const int &index, const int &height) 

      setRowHeight(index, height); 

      if (rowHeghtList.count() <= index + 1) { 

        rowHeghtList.append(height); 

      

      else

        rowHeghtList[index+1] = height; 

      

      tableHeight = 0; 

      for(int index = 0; index < rowHeghtList.count(); index++) 

         tableHeight += rowHeghtList.at(index); 

      resize(tableWidth, tableHeight); 

       

    void Table::createActions() 

      popMenu = new QMenu(); 

      actionName = new QAction(this); 

      actionSize = new QAction(this); 

      actionType = new QAction(this); 

      actionDate = new QAction(this); 

      actionOpen = new QAction(this);    

      actionDownload = new QAction(this); 

      actionFlush = new QAction(this); 

      actionDelete = new QAction(this); 

      actionRename = new QAction(this); 

      actionCreateFolder = new QAction(this); 

          

      actionOpen->setText(tr("打开")); 

      actionDownload->setText(tr("下载")); 

      actionFlush->setText(tr("刷新")); 

      actionDelete->setText(tr("删除")); 

      actionRename->setText(tr("重命名")); 

      actionCreateFolder->setText(tr("新建文件夹")); 

      actionName->setText(tr("名称")); 

      actionSize->setText(tr("大小")); 

      actionType->setText(tr("项目类型")); 

      actionDate->setText(tr("修改日期")); 

            

      actionFlush->setShortcut(QKeySequence::Refresh); 

      connect(actionRename, SIGNAL(triggered()), this, SLOT(slotActionRename())); 

       

    void Table::contextMenuEvent(QContextMenuEvent *event) 

      popMenu->clear(); 

      QPoint point = event->pos(); 

      rightClickedItem = this->itemAt(point); 

      if(rightClickedItem != NULL) { 

        popMenu->addAction(actionDownload); 

        popMenu->addAction(actionFlush); 

        popMenu->addSeparator(); 

        popMenu->addAction(actionDelete); 

        popMenu->addAction(actionRename); 

        popMenu->addSeparator(); 

        popMenu->addAction(actionCreateFolder); 

        QMenu *sortStyle = popMenu->addMenu(tr("排序")); 

        sortStyle->addAction(actionName); 

        sortStyle->addAction(actionSize); 

        sortStyle->addAction(actionType); 

        sortStyle->addAction(actionDate); 

               

        popMenu->exec(QCursor::pos()); 

        event->accept(); 

      

       

    QModelIndex Table::moveCursor(QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers) 

        //重写移动光标事件,当存在编辑项的时候,让光标永远位于当前项(编辑项),否则返回父类 

        if(rightClickedItem && rightClickedItem->row() >= 0) { 

            return currentIndex(); 

        

        else

           return QTableWidget::moveCursor(cursorAction, modifiers); 

        

       

       

    void Table::keyPressEvent(QKeyEvent *event) 

        if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { 

            QTableWidgetItem *item = currentItem(); 

            if (item) { 

                closePersistentEditor(item); 

                openPersistentEditor(item); 

                slotItemSelectionChanged(); 

                dupFlag = false; 

            

        

       

    void Table::slotItemSelectionChanged() 

        //关闭编辑项 

        if (rightClickedItem && dupFlag == false) { 

            int editRow = rightClickedItem->row(); 

            QTableWidgetItem *item = this->item(editRow, 0); 

            QMap<QTableWidgetItem *, QString>::iterator it; 

            for (it = fileMap.begin(); it != fileMap.end(); ++it) { 

                if (it.key() != item) { 

                    if (it.value() == item->text()) { 

                        dupFlag = true; 

                    

                

            

            if (dupFlag == false) { 

                this->closePersistentEditor(item); 

                rightClickedItem = NULL; 

            

            else

                QMessageBox::critical(this,tr("错误提示"),tr("文件重名"), tr("确定")); 

                setCurrentItem(item); 

            

        

        else

            dupFlag = false; 

        

       

    void Table::setItemFixed(bool flag) 

      if (flag == true) 

          horizontalHeader()->setResizeMode(QHeaderView::Fixed); 

      else 

          horizontalHeader()->setResizeMode(QHeaderView::Interactive); 

       

    bool Table::getSelectedRow(QList<int> &rowList) 

        //多选并获取所选行 

        QList<QTableWidgetItem *> items = this->selectedItems(); 

        int itemCount = items.count(); 

        if(itemCount <= 0) { 

            return false; 

        

        for (int index = 0; index < itemCount; index++) { 

            int itemRow = this->row(items.at(index)); 

            rowList.append(itemRow); 

        

        return  true; 

       

    void Table::slotItemEntered(QTableWidgetItem *item) 

      if(!item) 

        return

      QString name = item->text(); 

      if (name.isEmpty()) 

        return

      QToolTip::showText(QCursor::pos(), name); 

       

    void Table::slotActionRename() 

        //获得当前节点并获取编辑名称 

        if (rightClickedItem) { 

            int editRow = rightClickedItem->row(); 

            QTableWidgetItem *item = this->item(editRow, 0);   //编辑的行号及第一列 

            this->setCurrentCell(editRow, 0); 

            this->openPersistentEditor(item);                  //打开编辑项 

            this->editItem(item); 

        

    }

    Copy after login

(3) tablewidget.h

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    #ifndef TABLEWIDGET_H 

    #define TABLEWIDGET_H 

    #include "table.h" 

       

    class TableWidget : public QWidget 

        Q_OBJECT 

       

    public

        TableWidget(QWidget *parent = 0); 

        ~TableWidget(); 

       

    private

        bool ScanFile(const QString & path); 

       

    private

        Table *table; 

    }; 

       

    #endif // TABLEWIDGET_H

    Copy after login

(4)tablewidget.cpp


##

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

#include "tablewidget.h" 

   

TableWidget::TableWidget(QWidget *parent) 

    : QWidget(parent) 

    QTextCodec*codec = QTextCodec::codecForName("utf8"); 

    QTextCodec::setCodecForLocale(codec); 

    QTextCodec::setCodecForCStrings(codec); 

    QTextCodec::setCodecForTr(codec); 

    setWindowTitle(tr("文件浏览")); 

    table = new Table(this); 

   

    QStringList header; 

    header<<tr("文件名")<<tr("最后更改日期")<<tr("类型")<<tr("大小"); 

    table->setColumnValue(4, header); 

   

    table->setHeaderWidth(0, 200); 

    table->setHeaderWidth(1, 150); 

    table->setHeaderWidth(2, 100); 

    table->setHeaderWidth(3, 100); 

    table->setHeaderHeight(30); 

    //table->setRowH(0, 200); 

    ScanFile(QApplication::applicationDirPath()); 

//    table->setRowHeight(46); 

    resize(800, 800); 

   

TableWidget::~TableWidget() 

   

   

//Qt实现遍历文件夹和文件目录 

bool TableWidget::ScanFile(const QString &path) 

    QDir dir(path); 

    if (!dir.exists()) 

        return false; 

//    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot); 

//    QFileInfoList list = dir.entryInfoList(); 

//    //QStringList list = dir.entryList(); 

//    for(int index = 0; index < list.count(); index++) { 

//        QFileInfo fileInfo = list.at(index); 

//        if (fileInfo.isDir()) { 

//            ScanFile(fileInfo.filePath()); 

//        } 

//        else { 

//            qDebug() << "----------" << fileInfo.absoluteFilePath(); 

//        } 

//    } 

    QDirIterator dirIterator(path, QDir::Dirs | QDir::Files | QDir::NoSymLinks| QDir::NoDotAndDotDot, QDirIterator::Subdirectories); 

    while(dirIterator.hasNext()) { 

        dirIterator.next(); 

        QFileInfo fileInfo = dirIterator.fileInfo(); 

        QString filePath = fileInfo.absoluteFilePath(); 

        QFileIconProvider iconProvider; 

        QIcon icon; 

        if (fileInfo.isDir()) {          //获取指定文件图标 

            icon = iconProvider.icon(QFileIconProvider::Folder); 

        

        else

            icon = iconProvider.icon(fileInfo); 

        

        QFileIconProvider icon_provider; 

        QString typeFile = icon_provider.type(fileInfo); 

        table->addRowValue(30, QStringList()<< filePath <<fileInfo.lastModified().toString("yyyy-MM-dd hh:mm:ss"

                                            <<typeFile<<QString::number(fileInfo.size()/1024.0, &#39;f&#39;, 2)+"KB", icon); 

    

    return true; 

   

}

Copy after login
##(5)main.cpp

##

1

2

3

4

5

6

7

8

9

10

11

#include "tablewidget.h" 

#include <QApplication> 

   

int main(int argc, char *argv[]) 

    QApplication a(argc, argv); 

    TableWidget w; 

    w.show(); 

   

    return a.exec(); 

}

Copy after login

## (
6) Running results


##(7) Summary

Modified according to the online blog: The options clicked by the mouse will appear with a virtual box, create a right-click menu, obtain the file icon type, and right-click Tab key processing during editing, table updating after renaming files, and recursive scanning of folders.
2. QTableWidget control properties

1. Disable editing of the tableBy default, in the table The characters can be changed. For example, by double-clicking a cell, you can modify the original content. If you want to prohibit the user from doing this and make the table read-only for the user, you can do this:


  1. 1

    ui.qtablewidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    Copy after login

二、设置表格为选择整行

  1. 1

    2

    /*设置表格为整行选中*/ 

    ui.qtablewidget->setSelectionBehavior(QAbstractItemView::SelectRows);

    Copy after login

三、设置单个选中和多个选中
单个选中意味着每次只可以选中一个单元格,多个就是相当于可以选择”一片“那种模式。

  1. 1

    2

    /*设置允许多个选中*/  

    ui.qtablewidget->setSelectionMode(QAbstractItemView::ExtendedSelection);

    Copy after login

四、表格表头的显示与隐藏
对于水平或垂直方向的表头,如果不想显示可以用以下方式进行(隐藏/显示)设置:

  1. 1

    2

    ui.qtablewidget->verticalHeader()->setVisible(true);   

    ui.qtablewidget->horizontalHeader()->setVisible(false);

    Copy after login

五、设置具体单元格中字体的对齐方式

  1. 1

    ui.qtablewidget->item(0, 0)->setTextAlignment(Qt::AlignHCenter);

    Copy after login

六、设置具体单元格中字体格式

  1. 1

    2

    3

    ui.qtablewidget->item(1, 0)->setBackgroundColor(QColor(0,60,10));    

    ui.qtablewidget->item(1, 0)->setTextColor(QColor(200,111,100)); 

    ui.qtablewidget->item(1, 0)->setFont(QFont("Helvetica"));

    Copy after login

七、设置具体单元格的值

  1. 1

    ui.qtablewidget->setItem(1, 0, new QTableWidgetItem(str));

    Copy after login

八、把QTableWidgetItem对象内容转换为QString

  1. 1

    QString str =ui.qtablewidget->item(0, 0)->data(Qt::DisplayRole).toString();

    Copy after login

九、具体单元格中添加控件

  1. 1

    2

    3

    4

    QComboBox *comBox = new QComboBox(); 

    comBox->addItem("F"); 

    comBox->addItem("M"); 

    ui.qtablewidget->setCellWidget(0,3,comBox);

    Copy after login

十、合并单元格

  1. 1

    2

    3

    4

    5

    6

    //合并单元格的效果 

    ui.qtablewidget->setSpan(2, 2, 3, 2); 

    //第一个参数:要改变的单元格行数 

    //第二个参数:要改变的单元格列数 

    //第三个参数:需要合并的行数 

    //第四个参数:需要合并的列数

    Copy after login

十一、具体单元格中插入图片

  1. 1

    ui.qtablewidget->setItem(3, 2, new QTableWidgetItem(QIcon("images/music.png"), "Music"));

    Copy after login

十二、设置显示网格

  1. 1

    ui.qtablewidget->setShowGrid(true);//显示表格线

    Copy after login

十三、设置滚动条

  1. 1

    ui.qtablewidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//去掉水平滚动条

    Copy after login

十四、设置列标签

  1. 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    //初始化界面 

        QStringList  HStrList; 

        HStrList.push_back(QString("name")); 

        HStrList.push_back(QString("id")); 

        HStrList.push_back(QString("age")); 

        HStrList.push_back(QString("sex")); 

        HStrList.push_back(QString("department")); 

           

       

        //设置行列数(只有列存在的前提下,才可以设置列标签) 

        int HlableCnt = HStrList.count(); 

        ui.qtablewidget->setRowCount(10); 

        ui.qtablewidget->setColumnCount(HlableCnt); 

       

        //设置列标签 

        ui.qtablewidget->setHorizontalHeaderLabels(HStrList);

    Copy after login

十五、设置行和列的大小设为与内容相匹配

  1. 1

    2

    ui.qtablewidget->resizeColumnsToContents();   

    ui.qtablewidget->resizeRowsToContents();

    Copy after login

十六、设置字体

  1. 1

    ui.qtablewidget->setFont(font);   //设置字体

    Copy after login

十七、获取某一单元格的内容

  1. 1

    QString strText = ui.qtablewidget->item(0, 0)->text();

    Copy after login

3、QTableWidget美化

QSS样式表(根据需求修改颜色):

  1. 1

    2

    3

    4

    5

    6

    QTableWidget 

    background: rgb(56,56,56); 

    alternate-background-color:rgb(48,51,55); 

    selection-background-color:qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(56,56,56),stop:1 rgb(66,66,66)); 

    }

    Copy after login


  1. 1

    2

    3

    4

    5

    6

    QHeaderView::section 

    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(46,46,46),stop:1 rgb(56,56,56)); 

    color: rgb(210,210,210); 

    padding-left: 4px;border: 1px solid #383838; 

    }

    Copy after login


  1. 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    QScrollBar:vertical 

    border: 0px solid grey; 

    background: transparent; 

    width: 15px; 

    margin: 22px 0 22px 0; 

    QScrollBar::handle:vertical 

    background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 rgb(46,46,46),stop:1 rgb(66,66,66)); 

    min-height: 20px; 

    QScrollBar::add-line:vertical 

    border: 0px solid grey; 

    background: rgb(66,66,66); 

    height: 20px; 

    subcontrol-position: bottom; 

    subcontrol-origin: margin; 

    QScrollBar::sub-line:vertical 

    border: 0px solid grey; 

    background: rgb(56,56,56); 

    height: 20px; 

    subcontrol-position: top; 

    subcontrol-origin: margin; 

    QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical 

    border: 0px solid grey; 

    width: 3px; 

    height: 3px; 

    background: rgb(46,46,46); 

    QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical 

    background: none; 

    }

    Copy after login

四、总结

(1)源码中绝大部分的功能都没实现,Table也没进行完整的封装,可根据自己的需求修改代码。
(2)本代码的总结参考了网友的博客,在此感谢。

The above is the detailed content of Code implementation to create QT tables. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve win7 driver code 28 How to solve win7 driver code 28 Dec 30, 2023 pm 11:55 PM

Some users encountered errors when installing the device, prompting error code 28. In fact, this is mainly due to the driver. We only need to solve the problem of win7 driver code 28. Let’s take a look at what should be done. Do it. What to do with win7 driver code 28: First, we need to click on the start menu in the lower left corner of the screen. Then, find and click the "Control Panel" option in the pop-up menu. This option is usually located at or near the bottom of the menu. After clicking, the system will automatically open the control panel interface. In the control panel, we can perform various system settings and management operations. This is the first step in the nostalgia cleaning level, I hope it helps. Then we need to proceed and enter the system and

What to do if the blue screen code 0x0000001 occurs What to do if the blue screen code 0x0000001 occurs Feb 23, 2024 am 08:09 AM

What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

Solve the 'error: expected initializer before 'datatype'' problem in C++ code Solve the 'error: expected initializer before 'datatype'' problem in C++ code Aug 25, 2023 pm 01:24 PM

Solve the "error:expectedinitializerbefore'datatype'" problem in C++ code. In C++ programming, sometimes we encounter some compilation errors when writing code. One of the common errors is "error:expectedinitializerbefore'datatype'". This error usually occurs in a variable declaration or function definition and may cause the program to fail to compile correctly or

The computer frequently blue screens and the code is different every time The computer frequently blue screens and the code is different every time Jan 06, 2024 pm 10:53 PM

The win10 system is a very excellent high-intelligence system. Its powerful intelligence can bring the best user experience to users. Under normal circumstances, users’ win10 system computers will not have any problems! However, it is inevitable that various faults will occur in excellent computers. Recently, friends have been reporting that their win10 systems have encountered frequent blue screens! Today, the editor will bring you solutions to different codes that cause frequent blue screens in Windows 10 computers. Let’s take a look. Solutions to frequent computer blue screens with different codes each time: causes of various fault codes and solution suggestions 1. Cause of 0×000000116 fault: It should be that the graphics card driver is incompatible. Solution: It is recommended to replace the original manufacturer's driver. 2,

Resolve code 0xc000007b error Resolve code 0xc000007b error Feb 18, 2024 pm 07:34 PM

Termination Code 0xc000007b While using your computer, you sometimes encounter various problems and error codes. Among them, the termination code is the most disturbing, especially the termination code 0xc000007b. This code indicates that an application cannot start properly, causing inconvenience to the user. First, let’s understand the meaning of termination code 0xc000007b. This code is a Windows operating system error code that usually occurs when a 32-bit application tries to run on a 64-bit operating system. It means it should

Detailed explanation of the causes and solutions of 0x0000007f blue screen code Detailed explanation of the causes and solutions of 0x0000007f blue screen code Dec 25, 2023 pm 02:19 PM

Blue screen is a problem we often encounter when using the system. Depending on the error code, there will be many different reasons and solutions. For example, when we encounter the problem of stop: 0x0000007f, it may be a hardware or software error. Let’s follow the editor to find out the solution. 0x000000c5 blue screen code reason: Answer: The memory, CPU, and graphics card are suddenly overclocked, or the software is running incorrectly. Solution 1: 1. Keep pressing F8 to enter when booting, select safe mode, and press Enter to enter. 2. After entering safe mode, press win+r to open the run window, enter cmd, and press Enter. 3. In the command prompt window, enter "chkdsk /f /r", press Enter, and then press the y key. 4.

GE universal remote codes program on any device GE universal remote codes program on any device Mar 02, 2024 pm 01:58 PM

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

What does the blue screen code 0x000000d1 represent? What does the blue screen code 0x000000d1 represent? Feb 18, 2024 pm 01:35 PM

What does the 0x000000d1 blue screen code mean? In recent years, with the popularization of computers and the rapid development of the Internet, the stability and security issues of the operating system have become increasingly prominent. A common problem is blue screen errors, code 0x000000d1 is one of them. A blue screen error, or "Blue Screen of Death," is a condition that occurs when a computer experiences a severe system failure. When the system cannot recover from the error, the Windows operating system displays a blue screen with the error code on the screen. These error codes

See all articles