QT表格的实现

2023-05-16

本文章复制于别人的博客,是因为我怕原创者把原著删掉,所以就复制下来了,如有冒犯,请多见谅!

一、简介

        QTableWidget是QT对话框设计中常用的显示数据表格的控件,QTableWidget单元格数据是QTableWidgetItem对象来实现的,整个表格都需要用逐个单元格对象QTableWidgetItem构建起来。


二、详解

1、代码

(1)table.h

[html]  view plain  copy
  1. #ifndef TABLE_H  
  2. #define TABLE_H  
  3. #include <QtGui>  
  4.   
  5. class Table : public QTableWidget  
  6. {  
  7.     Q_OBJECT  
  8. public:  
  9.     Table(QWidget *parent = 0);  
  10.     ~Table();  
  11.     void setColumnValue(const int &columnSum, const QStringList &header);   //set header value  
  12.     void setHeaderWidth(const int &index, const int &width);    //set header and column widhth for each index  
  13.     void setHeaderHeight(const int &height);                    //set header height  
  14.   
  15.     void addRowValue(const int &height, const QStringList &value, const QIcon &fileIcon);  
  16.     void setRowH(const int &index, const int &height);  
  17.     void setItemFixed(bool flag);  
  18.     bool getSelectedRow(QList<int> &rowList);  
  19.       
  20. protected:  
  21.     void contextMenuEvent(QContextMenuEvent *event);  
  22.     QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);  
  23.     void keyPressEvent(QKeyEvent *event);  
  24.   
  25. private:  
  26.     void createActions();  
  27.       
  28. private slots:  
  29.     void slotItemEntered(QTableWidgetItem *item);  
  30.     void slotActionRename();  
  31.     void slotItemSelectionChanged();  
  32.       
  33. private:  
  34.     int tableWidth;  
  35.     int tableHeight;  
  36.     QList<int>rowHeghtList;  
  37.     QList<int>rowWidthList;  
  38.       
  39.     QMenu *popMenu;  
  40.     QAction *actionName;  
  41.     QAction *actionSize;  
  42.     QAction *actionType;  
  43.     QAction *actionDate;  
  44.     QAction *actionOpen;  
  45.     QAction *actionDownload;  
  46.     QAction *actionFlush;  
  47.     QAction *actionDelete;  
  48.     QAction *actionRename;  
  49.     QAction *actionCreateFolder;  
  50.     QTableWidgetItem *rightClickedItem;  
  51.     QMap<QTableWidgetItem *, QString>fileMap;  
  52.     bool dupFlag;  
  53. };  
  54.   
  55. // custom item delegate class  
  56. class NoFocusDelegate : public QStyledItemDelegate  
  57. {  
  58. protected:  
  59.     void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;  
  60. };  
  61. #endif // TABLE_H  
(2)table.cpp
[html]  view plain  copy
  1. #include "table.h"  
  2.   
  3. Table::Table(QWidget *parent)  
  4.     : QTableWidget(parent)  
  5.     , rightClickedItem(NULL)  
  6.     , dupFlag(false)  
  7. {  
  8.     rowHeghtList.clear();  
  9.     rowWidthList.clear();  
  10.     fileMap.clear();  
  11.     this->setMouseTracking(true);  
  12.     //setWindowTitle(tr("table"));  
  13.     horizontalHeader()->setDefaultSectionSize(100);  
  14.     verticalHeader()->setDefaultSectionSize(30);    //设置默认行高  
  15.     tableWidth = 100;  
  16.     tableHeight = 30;  
  17.     horizontalHeader()->setClickable(false);    //设置表头不可点击(默认点击后进行排序  
  18.   
  19.     QFont font = horizontalHeader()->font();    //设置表头字体加粗  
  20.     font.setBold(true);  
  21.     horizontalHeader()->setFont(font);  
  22.     horizontalHeader()->setStretchLastSection(true);    //设置充满表宽度  
  23.     horizontalHeader()->setMovable(false);              //表头左右互换  
  24.     //verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);  
  25.   
  26.     setFrameShape(QFrame::NoFrame);      //设置无边框  
  27.     //setShowGrid(false);                //设置不显示格子线  
  28.     verticalHeader()->setVisible(false); //设置垂直头不可见  
  29.     setSelectionMode(QAbstractItemView::ExtendedSelection);  //可多选(Ctrl、Shift、  Ctrl+A都可以)  
  30.     setSelectionBehavior(QAbstractItemView::SelectRows);  //设置选择行为时每次选择一行  
  31.     setEditTriggers(QAbstractItemView::NoEditTriggers); //设置不可编辑  
  32.   
  33.     setStyleSheet("selection-background-color:lightblue;");  //设置选中背景色  
  34.     //horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); //设置表头背景色  
  35.     //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));"); //设置选中背景色  
  36.     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;}"); //设置表头背景色  
  37.     setAlternatingRowColors(true);  
  38.   
  39.     //setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  
  40.     //setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  
  41.     //设置水平、垂直滚动条样式  
  42.     horizontalScrollBar()->setStyleSheet("QScrollBar{background:transparent; height:12px;}"  
  43.                                          "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"  
  44.                                          "QScrollBar::handle:hover{background:gray;}"  
  45.                                          "QScrollBar::sub-line{background:transparent;}"  
  46.                                          "QScrollBar::add-line{background:transparent;}");  
  47.   
  48.     verticalScrollBar()->setStyleSheet("QScrollBar{background:transparent; width:12px;}"  
  49.                                        "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"  
  50.                                        "QScrollBar::handle:hover{background:gray;}"  
  51.                                        "QScrollBar::sub-line{background:transparent;}"  
  52.                                        "QScrollBar::add-line{background:transparent;}");  
  53.   
  54.     // set the item delegate to your table widget  
  55.     setItemDelegate(new NoFocusDelegate());             //虚线边框去除  
  56.     //setFocusPolicy(Qt::NoFocus);   //去除选中虚线框  
  57.     horizontalHeader()->setHighlightSections(false);    //点击表时不对表头行光亮(获取焦点)  
  58.   
  59.     createActions();  
  60.     setItemFixed(false);  
  61.     connect(this, SIGNAL(itemEntered(QTableWidgetItem*)), this , SLOT(slotItemEntered(QTableWidgetItem*)));  
  62.     connect(this, SIGNAL(itemSelectionChanged()), this , SLOT(slotItemSelectionChanged()));  
  63.     //this->resize(600, 600);  
  64. }  
  65.   
  66. Table::~Table()  
  67. {  
  68.   
  69. }  
  70.   
  71. void Table::setColumnValue(const int &columnSum, const QStringList &header)  
  72. {  
  73.     setColumnCount(columnSum);                //设置列数  
  74.     this->setHorizontalHeaderLabels(header);  //设置列的标签  
  75. }  
  76.   
  77. void Table::setHeaderWidth(const int &index, const int &width)  
  78. {  
  79.     horizontalHeader()->resizeSection(index,width);  
  80.     if (rowWidthList.count() <= index + 1) {  
  81.       rowWidthList.append(width);  
  82.     }  
  83.     else {  
  84.       rowWidthList[index+1] = width;  
  85.     }  
  86.     tableWidth = 0;  
  87.     for(int index = 0; index < rowWidthList.count(); index++)  
  88.        tableWidth += rowWidthList.at(index);  
  89.     resize(tableWidth, tableHeight);  
  90. }  
  91.   
  92. void Table::setHeaderHeight(const int &height)  
  93. {  
  94.     horizontalHeader()->setFixedHeight(height);        //设置表头的高度  
  95.     if (rowHeghtList.isEmpty()) {  
  96.       rowHeghtList.append(height);  
  97.     }  
  98.     else {  
  99.       rowHeghtList[0] = height;  
  100.     }  
  101.     tableHeight = 0;  
  102.     for(int index = 0; index < rowHeghtList.count(); index++)  
  103.        tableHeight += rowHeghtList.at(index);  
  104.     resize(tableWidth, tableHeight);  
  105. }  
  106.   
  107. void Table::addRowValue(const int &height, const QStringList &value, const QIcon &fileIcon)  
  108. {  
  109.     int row_count = rowCount();    //获取表单行数  
  110.     insertRow(row_count);          //插入新行  
  111.     setRowHeight(row_count, height);  
  112.     for (int index = 0; index < columnCount(); index++) {  
  113.         QTableWidgetItem *item = new QTableWidgetItem;  
  114.         if (index == 0) {  
  115.             item->setIcon(fileIcon);  
  116.             item->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft);  
  117.             fileMap.insert(item, value.at(index));  
  118.         }  
  119.         else {  
  120.             item->setTextAlignment(Qt::AlignCenter);  
  121.         }  
  122.         item->setText(value.at(index));  
  123.         setItem(row_count, index, item);  
  124.     }  
  125.     rowHeghtList.append(height);  
  126.     tableHeight += height;   
  127.     resize(tableWidth, tableHeight);  
  128. }  
  129.   
  130.   
  131. void NoFocusDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const  
  132. {  
  133.     QStyleOptionViewItem itemOption(option);  
  134.     if (itemOption.state & QStyle::State_HasFocus)  
  135.         itemOption.state = itemOption.state ^ QStyle::State_HasFocus;  
  136.     QStyledItemDelegate::paint(painter, itemOption, index);  
  137. }  
  138.   
  139. void Table::setRowH(const int &index, const int &height)  
  140. {  
  141.   setRowHeight(index, height);  
  142.   if (rowHeghtList.count() <= index + 1) {  
  143.     rowHeghtList.append(height);  
  144.   }  
  145.   else {  
  146.     rowHeghtList[index+1] = height;  
  147.   }  
  148.   tableHeight = 0;  
  149.   for(int index = 0; index < rowHeghtList.count(); index++)  
  150.      tableHeight += rowHeghtList.at(index);  
  151.   resize(tableWidth, tableHeight);  
  152. }  
  153.   
  154. void Table::createActions()  
  155. {  
  156.   popMenu = new QMenu();  
  157.   actionName = new QAction(this);  
  158.   actionSize = new QAction(this);  
  159.   actionType = new QAction(this);  
  160.   actionDate = new QAction(this);  
  161.   actionOpen = new QAction(this);     
  162.   actionDownload = new QAction(this);  
  163.   actionFlush = new QAction(this);  
  164.   actionDelete = new QAction(this);  
  165.   actionRename = new QAction(this);  
  166.   actionCreateFolder = new QAction(this);  
  167.      
  168.   actionOpen->setText(tr("打开"));  
  169.   actionDownload->setText(tr("下载"));  
  170.   actionFlush->setText(tr("刷新"));  
  171.   actionDelete->setText(tr("删除"));  
  172.   actionRename->setText(tr("重命名"));  
  173.   actionCreateFolder->setText(tr("新建文件夹"));  
  174.   actionName->setText(tr("名称"));  
  175.   actionSize->setText(tr("大小"));  
  176.   actionType->setText(tr("项目类型"));  
  177.   actionDate->setText(tr("修改日期"));  
  178.        
  179.   actionFlush->setShortcut(QKeySequence::Refresh);  
  180.   connect(actionRename, SIGNAL(triggered()), this, SLOT(slotActionRename()));  
  181. }  
  182.   
  183. void Table::contextMenuEvent(QContextMenuEvent *event)  
  184. {  
  185.   popMenu->clear();  
  186.   QPoint point = event->pos();  
  187.   rightClickedItem = this->itemAt(point);  
  188.   if(rightClickedItem != NULL) {  
  189.     popMenu->addAction(actionDownload);  
  190.     popMenu->addAction(actionFlush);  
  191.     popMenu->addSeparator();  
  192.     popMenu->addAction(actionDelete);  
  193.     popMenu->addAction(actionRename);  
  194.     popMenu->addSeparator();  
  195.     popMenu->addAction(actionCreateFolder);  
  196.     QMenu *sortStyle = popMenu->addMenu(tr("排序"));  
  197.     sortStyle->addAction(actionName);  
  198.     sortStyle->addAction(actionSize);  
  199.     sortStyle->addAction(actionType);  
  200.     sortStyle->addAction(actionDate);  
  201.           
  202.     popMenu->exec(QCursor::pos());  
  203.     event->accept();  
  204.   }  
  205. }  
  206.   
  207. QModelIndex Table::moveCursor(QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers)  
  208. {  
  209.     //重写移动光标事件,当存在编辑项的时候,让光标永远位于当前项(编辑项),否则返回父类  
  210.     if(rightClickedItem && rightClickedItem->row() >= 0) {  
  211.         return currentIndex();  
  212.     }  
  213.     else {  
  214.        return QTableWidget::moveCursor(cursorAction, modifiers);  
  215.     }  
  216. }  
  217.   
  218.   
  219. void Table::keyPressEvent(QKeyEvent *event)  
  220. {  
  221.     if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {  
  222.         QTableWidgetItem *item = currentItem();  
  223.         if (item) {  
  224.             closePersistentEditor(item);  
  225.             openPersistentEditor(item);  
  226.             slotItemSelectionChanged();  
  227.             dupFlag = false;  
  228.         }  
  229.     }  
  230. }  
  231.   
  232. void Table::slotItemSelectionChanged()  
  233. {  
  234.     //关闭编辑项  
  235.     if (rightClickedItem && dupFlag == false) {  
  236.         int editRow = rightClickedItem->row();  
  237.         QTableWidgetItem *item = this->item(editRow, 0);  
  238.         QMap<QTableWidgetItem *, QString>::iterator it;  
  239.         for (it = fileMap.begin(); it != fileMap.end(); ++it) {  
  240.             if (it.key() != item) {  
  241.                 if (it.value() == item->text()) {  
  242.                     dupFlag = true;  
  243.                 }  
  244.             }  
  245.         }  
  246.         if (dupFlag == false) {  
  247.             this->closePersistentEditor(item);  
  248.             rightClickedItem = NULL;  
  249.         }  
  250.         else {  
  251.             QMessageBox::critical(this,tr("错误提示"),tr("文件重名"), tr("确定"));  
  252.             setCurrentItem(item);  
  253.         }  
  254.     }  
  255.     else {  
  256.         dupFlag = false;  
  257.     }  
  258. }  
  259.   
  260. void Table::setItemFixed(bool flag)  
  261. {  
  262.   if (flag == true)  
  263.       horizontalHeader()->setResizeMode(QHeaderView::Fixed);  
  264.   else  
  265.       horizontalHeader()->setResizeMode(QHeaderView::Interactive);  
  266. }  
  267.   
  268. bool Table::getSelectedRow(QList<int> &rowList)  
  269. {  
  270.     //多选并获取所选行  
  271.     QList<QTableWidgetItem *> items = this->selectedItems();  
  272.     int itemCount = items.count();  
  273.     if(itemCount <= 0) {  
  274.         return false;  
  275.     }  
  276.     for (int index = 0; index < itemCount; index++) {  
  277.         int itemRow = this->row(items.at(index));  
  278.         rowList.append(itemRow);  
  279.     }  
  280.     return  true;  
  281. }  
  282.   
  283. void Table::slotItemEntered(QTableWidgetItem *item)  
  284. {  
  285.   if(!item)  
  286.     return;  
  287.   QString name = item->text();  
  288.   if (name.isEmpty())  
  289.     return;  
  290.   QToolTip::showText(QCursor::pos(), name);  
  291. }  
  292.   
  293. void Table::slotActionRename()  
  294. {  
  295.     //获得当前节点并获取编辑名称  
  296.     if (rightClickedItem) {  
  297.         int editRow = rightClickedItem->row();  
  298.         QTableWidgetItem *item = this->item(editRow, 0);   //编辑的行号及第一列  
  299.         this->setCurrentCell(editRow, 0);  
  300.         this->openPersistentEditor(item);                  //打开编辑项  
  301.         this->editItem(item);  
  302.     }  
  303. }  
(3)tablewidget.h
[html]  view plain  copy
  1. #ifndef TABLEWIDGET_H  
  2. #define TABLEWIDGET_H  
  3. #include "table.h"  
  4.   
  5. class TableWidget : public QWidget  
  6. {  
  7.     Q_OBJECT  
  8.   
  9. public:  
  10.     TableWidget(QWidget *parent = 0);  
  11.     ~TableWidget();  
  12.   
  13. private:  
  14.     bool ScanFile(const QString & path);  
  15.   
  16. private:  
  17.     Table *table;  
  18. };  
  19.   
  20. #endif // TABLEWIDGET_H  
(4)tablewidget.cpp
[html]  view plain  copy
  1. #include "tablewidget.h"  
  2.   
  3. TableWidget::TableWidget(QWidget *parent)  
  4.     : QWidget(parent)  
  5. {  
  6.     QTextCodec*codec = QTextCodec::codecForName("utf8");  
  7.     QTextCodec::setCodecForLocale(codec);  
  8.     QTextCodec::setCodecForCStrings(codec);  
  9.     QTextCodec::setCodecForTr(codec);  
  10.     setWindowTitle(tr("文件浏览"));  
  11.     table = new Table(this);  
  12.   
  13.     QStringList header;  
  14.     header<<tr("文件名")<<tr("最后更改日期")<<tr("类型")<<tr("大小");  
  15.     table->setColumnValue(4, header);  
  16.   
  17.     table->setHeaderWidth(0, 200);  
  18.     table->setHeaderWidth(1, 150);  
  19.     table->setHeaderWidth(2, 100);  
  20.     table->setHeaderWidth(3, 100);  
  21.     table->setHeaderHeight(30);  
  22.     //table->setRowH(0, 200);  
  23.     ScanFile(QApplication::applicationDirPath());  
  24. //    table->setRowHeight(46);  
  25.     resize(800, 800);  
  26. }  
  27.   
  28. TableWidget::~TableWidget()  
  29. {  
  30.   
  31. }  
  32.   
  33. //Qt实现遍历文件夹和文件目录  
  34. bool TableWidget::ScanFile(const QString &path)  
  35. {  
  36.     QDir dir(path);  
  37.     if (!dir.exists())  
  38.         return false;  
  39. //    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);  
  40. //    QFileInfoList list = dir.entryInfoList();  
  41. //    //QStringList list = dir.entryList();  
  42. //    for(int index = 0; index < list.count(); index++) {  
  43. //        QFileInfo fileInfo = list.at(index);  
  44. //        if (fileInfo.isDir()) {  
  45. //            ScanFile(fileInfo.filePath());  
  46. //        }  
  47. //        else {  
  48. //            qDebug() << "----------" << fileInfo.absoluteFilePath();  
  49. //        }  
  50. //    }  
  51.     QDirIterator dirIterator(path, QDir::Dirs | QDir::Files | QDir::NoSymLinks| QDir::NoDotAndDotDot, QDirIterator::Subdirectories);  
  52.     while(dirIterator.hasNext()) {  
  53.         dirIterator.next();  
  54.         QFileInfo fileInfo = dirIterator.fileInfo();  
  55.         QString filePath = fileInfo.absoluteFilePath();  
  56.         QFileIconProvider iconProvider;  
  57.         QIcon icon;  
  58.         if (fileInfo.isDir()) {          //获取指定文件图标  
  59.             icon = iconProvider.icon(QFileIconProvider::Folder);  
  60.         }  
  61.         else {  
  62.             icon = iconProvider.icon(fileInfo);  
  63.         }  
  64.         QFileIconProvider icon_provider;  
  65.         QString typeFile = icon_provider.type(fileInfo);  
  66.         table->addRowValue(30, QStringList()<< filePath <<fileInfo.lastModified().toString("yyyy-MM-dd hh:mm:ss")  
  67.                                             <<typeFile<<QString::number(fileInfo.size()/1024.0, 'f', 2)+"KB", icon);  
  68.     }  
  69.     return true;  
  70.   
  71. }  
(5)main.cpp
[html]  view plain  copy
  1. #include "tablewidget.h"  
  2. #include <QApplication>  
  3.   
  4. int main(int argc, char *argv[])  
  5. {  
  6.     QApplication a(argc, argv);  
  7.     TableWidget w;  
  8.     w.show();  
  9.   
  10.     return a.exec();  
  11. }  
(6)运行结果

(7)总结
        根据网上博客修改了:鼠标点击的选项会出现虚框、创建右键菜单、获取文件图标类型、右键编辑时Tab键的处理和重命名文件重名后表格更新的、递归扫描文件夹。

2、QTableWidget控件属性

一、禁止编辑表格
在默认情况下,表格里的字符是可以更改的。
比如双击一个单元格,就可以修改原来的内容,如果想禁止用户的这种操作,让这个表格对用户只读,可以这样:
[html]  view plain  copy
  1. ui.qtablewidget->setEditTriggers(QAbstractItemView::NoEditTriggers);  
二、设置表格为选择整行
[html]  view plain  copy
  1. /*设置表格为整行选中*/  
  2. ui.qtablewidget->setSelectionBehavior(QAbstractItemView::SelectRows);  
三、设置单个选中和多个选中
单个选中意味着每次只可以选中一个单元格,多个就是相当于可以选择”一片“那种模式。
[html]  view plain  copy
  1. /*设置允许多个选中*/   
  2. ui.qtablewidget->setSelectionMode(QAbstractItemView::ExtendedSelection);  
四、表格表头的显示与隐藏
对于水平或垂直方向的表头,如果不想显示可以用以下方式进行(隐藏/显示)设置:
[html]  view plain  copy
  1. ui.qtablewidget->verticalHeader()->setVisible(true);    
  2. ui.qtablewidget->horizontalHeader()->setVisible(false);  
五、设置具体单元格中字体的对齐方式
[html]  view plain  copy
  1. ui.qtablewidget->item(0, 0)->setTextAlignment(Qt::AlignHCenter);  
六、设置具体单元格中字体格式
[html]  view plain  copy
  1. ui.qtablewidget->item(1, 0)->setBackgroundColor(QColor(0,60,10));     
  2. ui.qtablewidget->item(1, 0)->setTextColor(QColor(200,111,100));  
  3. ui.qtablewidget->item(1, 0)->setFont(QFont("Helvetica"));   
七、设置具体单元格的值
[html]  view plain  copy
  1. ui.qtablewidget->setItem(1, 0, new QTableWidgetItem(str));  
八、把QTableWidgetItem对象内容转换为QString
[html]  view plain  copy
  1. QString str =ui.qtablewidget->item(0, 0)->data(Qt::DisplayRole).toString();  
九、具体单元格中添加控件
[html]  view plain  copy
  1. QComboBox *comBox = new QComboBox();  
  2. comBox->addItem("F");  
  3. comBox->addItem("M");  
  4. ui.qtablewidget->setCellWidget(0,3,comBox);  
十、合并单元格
[html]  view plain  copy
  1. //合并单元格的效果  
  2. ui.qtablewidget->setSpan(2, 2, 3, 2);  
  3. //第一个参数:要改变的单元格行数  
  4. //第二个参数:要改变的单元格列数  
  5. //第三个参数:需要合并的行数  
  6. //第四个参数:需要合并的列数  
十一、具体单元格中插入图片
[html]  view plain  copy
  1. ui.qtablewidget->setItem(3, 2, new QTableWidgetItem(QIcon("images/music.png"), "Music"));  
十二、设置显示网格
[html]  view plain  copy
  1. ui.qtablewidget->setShowGrid(true);//显示表格线  
十三、设置滚动条
[html]  view plain  copy
  1. ui.qtablewidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//去掉水平滚动条  
十四、设置列标签
[html]  view plain  copy
  1. //初始化界面  
  2.     QStringList  HStrList;  
  3.     HStrList.push_back(QString("name"));  
  4.     HStrList.push_back(QString("id"));  
  5.     HStrList.push_back(QString("age"));  
  6.     HStrList.push_back(QString("sex"));  
  7.     HStrList.push_back(QString("department"));  
  8.       
  9.   
  10.     //设置行列数(只有列存在的前提下,才可以设置列标签)  
  11.     int HlableCnt = HStrList.count();  
  12.     ui.qtablewidget->setRowCount(10);  
  13.     ui.qtablewidget->setColumnCount(HlableCnt);  
  14.   
  15.     //设置列标签  
  16.     ui.qtablewidget->setHorizontalHeaderLabels(HStrList);  
十五、设置行和列的大小设为与内容相匹配
[html]  view plain  copy
  1. ui.qtablewidget->resizeColumnsToContents();    
  2. ui.qtablewidget->resizeRowsToContents();    
十六、设置字体
[html]  view plain  copy
  1. ui.qtablewidget->setFont(font);   //设置字体  
十七、 获取某一单元格的内容
[html]  view plain  copy
  1. QString strText = ui.qtablewidget->item(0, 0)->text();  

3、QTableWidget美化

QSS样式表(根据需求修改颜色):
[html]  view plain  copy
  1. QTableWidget  
  2. {  
  3. background: rgb(56,56,56);  
  4. alternate-background-color:rgb(48,51,55);  
  5. selection-background-color:qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(56,56,56),stop:1 rgb(66,66,66));  
  6. }  
[html]  view plain  copy
  1. QHeaderView::section  
  2. {  
  3. background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(46,46,46),stop:1 rgb(56,56,56));  
  4. color: rgb(210,210,210);  
  5. padding-left: 4px;border: 1px solid #383838;  
  6. }  
[html]  view plain  copy
  1. QScrollBar:vertical  
  2. {  
  3. border: 0px solid grey;  
  4. background: transparent;  
  5. width: 15px;  
  6. margin: 22px 0 22px 0;  
  7. }  
  8. QScrollBar::handle:vertical  
  9. {  
  10. background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 rgb(46,46,46),stop:1 rgb(66,66,66));  
  11. min-height: 20px;  
  12. }  
  13. QScrollBar::add-line:vertical  
  14. {  
  15. border: 0px solid grey;  
  16. background: rgb(66,66,66);  
  17. height: 20px;  
  18. subcontrol-position: bottom;  
  19. subcontrol-origin: margin;  
  20. }  
  21. QScrollBar::sub-line:vertical  
  22. {  
  23. border: 0px solid grey;  
  24. background: rgb(56,56,56);  
  25. height: 20px;  
  26. subcontrol-position: top;  
  27. subcontrol-origin: margin;  
  28. }  
  29. QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical  
  30. {  
  31. border: 0px solid grey;  
  32. width: 3px;  
  33. height: 3px;  
  34. background: rgb(46,46,46);  
  35. }  
  36. QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical  
  37. {  
  38. background: none;  
  39. }  

四、总结

(1)源码中绝大部分的功能都没实现,Table也没进行完整的封装,可根据自己的需求修改代码。
(2)本代码的总结参考了网友的博客,在此感谢。
(3)源码已经打包上传到csdn上,可登录下载(http://download.csdn.net/detail/taiyang1987912/8938815)。
(4)若有建议,请留言,在此先感谢! 

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/taiyang1987912/article/details/47043937
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

QT表格的实现 的相关文章

  • 上位机与下位机通信

    本文链接地址 上位机与下位机通信 Content STM32串口发送与接收ROS串口发送与接收 一般情况 xff0c 上位机由ROS框架运行在Ubuntu的树莓派构成 xff0c 下位机由STM32F103VET6芯片板载电机 xff0c
  • 【电子技术实验设计】课程设计题目

    电子技术基础 课程设计题目 题目一一 声控照明系统的设计二 报警声响发生器的设计三 水位控制器的设计四 金属探测器的设计五 循环灯控制系统的设计六 数字水位探测器的设计七 直流电压升压器的设计八 上下课铃声识别系统的设计九 厕所冲水控制器的
  • 【电子技术实验设计】简易交通灯控制逻辑电路设计报告

    简易交通灯控制逻辑电路设计报告 一 设计任务和要求二 设计目的三 设计方案选择方案一方案二方案一 优点 xff1a 状态转换简单 xff1b 方案二 优点 xff1a 下降脉冲触发 xff0c 与时钟信号匹配 xff1b 方案框图 四 单元
  • 【电子技术实验】NE555中文数据手册

    NE555中文资料 NE555P概述封装外形图封装特点功能框图 555端口描述 xff08 5脚 8脚 xff09 555管脚功能介绍 xff1a 应用图单稳态延时电路多谐振荡电路开机延时电路开机延迟电路 xff1a NE555P 概述 N
  • 【电子技术实验】555定时器秒脉冲时钟电路

    555定时器秒脉冲时钟电路 秒信号发生电路由集成电路555定时器与RC组成的多谐振荡器构成 需要的芯片有集成电路555定时器 xff0c 还有电阻和电容 计算公式 f 61 1 43 xff3b xff08 R1 43 2R2 xff09
  • 【Prometheus二次开发课程 】01 Prometheus简介 (学习笔记)

    文章目录 Prometheus全自主无人机开源软件平台项目创始人介绍 背景多旋翼无人机发展历史 xff1a 多旋翼无人机的优势多旋翼无人机的应用场景什么是自主无人机 xff1f 无人机的基本组成 xff08 航模 xff09 PX4生态系统
  • 【PX4 二次开发 初级】 02 飞控软硬件体系

    PX4 二次开发初级 PX4 飞控软硬件体系 飞控硬件体系PIXHAWK 控制硬件 软件体系PX4 体系原生固件原生固件官网原生固件地面站 APM 体系APM官网 xff1a 原生固件地面站 特点 标题 xff1a PX4二次开发教程 xf
  • 【PX4 二次开发 初级】 03 飞控调试以及地面站使用

    PX4 二次开发 初级 03 飞控调试以及地面站使用 前言IMU三轴稳定性内部构成陀螺仪加速度计磁力计 误差加速度 amp 陀螺仪 磁力计干扰测试 标题 xff1a PX4二次开发教程 xff1a 起源 xff1a 根据阿木实验室讲解课程整
  • 【嵌入式】牧马人G3 电子竞技鼠标拆解分析

    嵌入式 牧马人G3 电子竞技鼠标拆解分析 拆解性能以及构造A702 A704 数据手册引脚图引脚说明功能应用电路图 拆解 拆解后机械鼠标 生前图标 四个螺丝拆掉 左右两侧螺栓拆掉 上壳扒开 垫片剔除 xff0c 然后拔出隐藏在垫片下的螺栓
  • 【Mavros解析 】01 ROS消息以及常用指令

    Mavros解析 01ROS消息以及常用指令 示例代码一示例一代码解析ROS初始化消息订阅 xff1a 模板函数定时器回调循环睡眠函数 示例代码二示例二解析公布消息模板函数 标题 xff1a MAVROS教程 offboard模式下自主飞行
  • 【Mavros解析 】02 ROS服务以及在mavros中体现

    Mavros解析 02 ROS服务以及在mavros中体现 简介实现步骤步骤 1 xff1a 连接服务步骤 2 xff1a 实例化服务参数 xff1a 步骤 3 xff1a 请求服务 Demo头文件订阅回调函数主函数初始化订阅mavrso
  • Pixhawk---通过串口方式添加一个自定义传感器(超声波为例)

    xfeff xfeff Pixhawk 添加一个自定义传感器 超声波 xff08 串口方式 xff09 1 说明 首先超声波模块是通过串口方式发送 xff08 Tx xff09 出数据 xff0c 使用的模块数据发送周期为100ms xff
  • 【PX4 飞控剖析】01 offborad模式的开发与应用

    PX4 飞控剖析 01 offborad模式的开发与应用 offboard模式的开发及应用px4固件的模式自定义模式auto子模式外部模式应用场合 offboard模式的开发及应用 px4固件的模式 px4固件支持10几种飞行模式 xff0
  • 【mavros源码解析】10 MAVROS包含文件及消息机制

    Mavros解析 10 mavros源码 Mavros简介Mavros代码详解libmavconn xff1a mavros xff1a mavros extras mavros msgs MAVROS 包含文件include launch
  • 【PX4 飞控剖析】03 PX4固件烧录以及调试指南

    PX4 飞控剖析 03 PX4固件烧录以及QGC初步指南 一 加载固件二 加载参数三 校准传感器四 遥控器校准五 飞行模式六 电调校准七 检查参数 标题 xff1a PX4 飞控剖析 03 PX4固件烧录以及调试指南起源 xff1a 根据阿
  • 【PX4 飞控剖析】05 PIX4 连接QGC 可以烧录固件但是连接不上

    PX4 飞控剖析 05 PIX4 连接QGC 可以烧录固件但是连接不上 总结 如图 xff1a QGC error link Device on COM3 Error connecting Could not create port 这个是
  • 【SLAM】英特尔D455与D435i的区别

    SLAM 英特尔D455与D435i的区别 参考链接 xff1a bing搜索 D455 深度摄像头 官方介绍 D455 机械尺度更大 视场角范围更广 视场角更宽 同时RGB 传感器技术 支持全局快门 xff0c 如果对视野范围有要求的用户
  • Bubble Planner无人机运动规划算法解读

    Bubble Planner无人机运动规划算法解读 本文将介绍一种无人机的在线路径规划算法 Bubble Planner xff0c Bubble Planner 是港大张富老师MaRS实验室提出了一种的新型规划算法 xff0c 是一种用于
  • 【论文研读】无人机飞行模拟仿真平台设计

    无人机飞行模拟仿真平台设计 摘要 xff1a 为提高飞行控制算法的研发效率 降低研发成本 基于数字孪生技术设计一个无人机硬件在环飞行模拟仿真平台 从几何 物理和行为3个方面研究无人机数字模型构建方法 将物理实体以数字化方式呈现 设计一种多元

随机推荐

  • 【深度学习基础】

    最终效果如上图所示 xff1a 真不知道这一路有多艰难 众所周知CHATGPT 可以做表格和 公式 xff0c 但它输出的文本是直接渲染好的 你是直接复制不了的 xff0c 你只能复制它出来的字体 于是我尝试了各种 想让它输出表格和文字的方
  • 【蛤蟆先生去看心理医生】

    第一章 整个人都不太好 人物性格描述蛤蟆热情 时尚 爱冒险 xff0c 现在抑郁 xff0c 不能自拔獾智慧 威严河鼠关心朋友 xff0c 有点絮叨鼹鼠体贴善良 第二章 擎友前来相助 讲诉了鼹鼠和河鼠对蛤蟆情况的担忧和讨论 鼹鼠回忆起过去蛤
  • linux下tar、zip、rar解压缩命令使用

    zip 命令 将当前目录下的所有文件和文件夹全部压缩成myfile zip zip r myfile zip r表示递归压缩子目录下所有文件 把myfile zip文件解压到 home sunny unzip o d home sunny
  • Pixhawk—添加一个自定义传感器—超声波(串口方式)

    xfeff xfeff 版权声明 xff1a 本文为博主 原创 文章 xff0c 未经博主允许可以转载 xff0c 注明博客出处 xff1a http blog csdn net FreeApe 目录 43 Pixhawk添加一个自定义传感
  • parson例说

    例说 以JSON中国网站的例子 xff0c 测试代码 include 34 parson h 34 include lt stdio h gt include lt stdlib h gt void test write void void
  • IAR编译优化

    IAREWARM编译器和其他厂家的C编译器相比非常高效 但是当程序里面包含对时序要求比较严格的代码的时候 IAR常常会把这些代码过渡优化 破坏了时序的要求 造成程序错误 在程序代码比较紧的时候又必须优化 可以在要求比较严格的代码的函数前面
  • 在树莓派上使用GPS模块

    GPSD介绍 GPSD是一个Linux下的一个守护进程 xff0c 用以侦听来自GPS接收器的位置等信息 xff0c 并将这些位置信息转换成一种简化的格式 GPSD支持二十多种不同GPS输出格式的GPS接收机 xff0c 例如NMEA As
  • 用两片74HC138组合成4/16译码器

    译码器很多 xff0c 常见的有2路译码器 xff08 74HC139D 2路2 4译码器 多路复用器 xff09 xff0c 3 8译码器 xff08 74HC138D 三八译码器 解码器 xff09 和4 16译码器 xff08 74H
  • virtual method but non-virtual destructor

    有虚函数 xff08 纯虚函数 xff09 就应该有虚析构函数 class Base public virtual void func 61 0 virtual Base 注意 xff0c 有 实现 class Child public B
  • STM32使用C标准库time.h里面的时间时钟函数

    标准C里面已经定义好时间日期库time h xff0c 在嵌入式里面并没有被限制使用 下面我们看一下怎样在IAR中使用time h库 有四个与时间相关的类型 xff1a clock t time t size t 和 tm 类型 clock
  • ros 学习之计算机视觉资料总结

    ros 学习之计算机视觉 ros高效编程Visual ServoingAugmented Reality xff08 AR xff09 Perception and object recognitionvisual odometry 古月居
  • 数字信号处理 离散时间信号

    1 时域离散信号 xff1a 对模拟信号进行等间隔采样 xff0c 即得到时域离散信号 xff08 时间离散 xff0c 但是幅度没有量化 xff0c 离散 xff09 1 xff09 例如 对连续信号Xa t 以等间隔T对其进行采样 xf
  • 复指数函数

    复指数信号 百度百科 复指数信号是指数信号的指数因子是复数时 xff0c 称之为复指数信号 复指数信号在物理上是不可实现的 xff0c 但是它概括了多种情况 利用复指数信号可以表示常见的普通信号 xff0c 如直流信号 指数信号 正弦信号等
  • Make 详解

    1 windows的IDE中自带Makefile 但是unix和linux需要自己写 2 makefile除了指定文件的编译顺序和规则以外 xff0c 也可以执行操作系统的命令 3 make 是一个命令工具 xff0c 是一个解释makef
  • 四旋翼无人机飞行控制算法H∞控制

    PID控制之所以被广泛应用 xff0c 就是因为它是一个无模型控制器 也就是说 xff0c 不管控制对象是什么 xff0c PID控制器的公式都是现成的 xff0c 然后你去修改三个参数试凑就行了 这对理论基础较差的工程技术人员来说用起来是
  • 【无标题】

    linux常用的压缩格式为 xff1a zip tar gz tar tar bz2等 xff0c 不同的方式消耗的时间和压缩比差异比较大 1 zip zip r test zip test r 表示当前test是个目录 2 解压命令 xf
  • 【无标题】

    如下是读取16bit音频raw文件的程序 xff0c 其中的short就是为了16bit准备的 xff0c 一般的固定频率的单频 xff08 1khz之类 xff09 的音频文件是固定的循环 xff0c 比如1khz是每8个点循环一次 xf
  • select 的使用

    select是在指定时间内 xff08 最后一个参数指定的时间 xff09 轮询指定fd集合的接口 1 需要包含的头文件 include lt sys time h gt select是在指定时间内轮询 xff0c 所以有时间相关的参数 i
  • KEIL修改背景色

    本篇文章借鉴 于旺园先生的 平时在用keil软件比较多 xff0c 看白色背景比较多有点伤眼睛 xff0c 现在我们来设置一下keil的背景 xff0c 来保护我们的眼睛吧 效果图 xff1a 1 打开配置界面 color amp font
  • QT表格的实现

    本文章复制于别人的博客 xff0c 是因为我怕原创者把原著删掉 xff0c 所以就复制下来了 xff0c 如有冒犯 xff0c 请多见谅 xff01 一 简介 QTableWidget是QT对话框设计中常用的显示数据表格的控件 xff0c