QTableWidget常用函數及注意事項


0 常用設置

  //table setting
  //設置表頭
  QStringList header;
  header<< "ID" << "Info1"<<"info2" << "info3";
  ui->tableWidget_1->setHorizontalHeaderLabels(header);
  //整行選中的方式
  ui->tableWidget_1->setSelectionBehavior(QAbstractItemView::SelectRows); 
  //禁止修改
  ui->tableWidget_1->setEditTriggers(QAbstractItemView::NoEditTriggers); 
  //顯示列表頭
  ui->tableWidget_1->verticalHeader()->setVisible(true); 
  //開啟自動滾動
  ui->tableWidget_1->setAutoScroll(true);
   // end table setting

 

 

1 添加表頭內容

  QStringList header;
  header<<""<<tr("1")<<tr("2")<<tr("3")<<tr("4)<<tr("5");
  tableWidget->setHorizontalHeaderLabels(header);


2 設置表格:整行選擇
  tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
  其他參數:
    QAbstractItemView.SelectItems 選中單個單元格
    QAbstractItemView.SelectRows 選中一行
    QAbstractItemView.SelectColumns 選中一列


3 設置表格編輯方式
  tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
  其他參數:
    QAbstractItemView.NoEditTriggers 不對表格內容進行修改
    QAbstractItemView.CurrentChanged 任何時候都能對單元格修改
    QAbstractItemView.DoubleClicked 雙擊單元格
    QAbstractItemView.SelectedClicked 單擊已選中的內容
    QAbstractItemView.EditKeyPressed 按下編輯鍵后編輯
    QAbstractItemView.AnyKeyPressed 按下任意鍵就能編輯
    QAbstractItemView.AllEditTriggers 以上條件全包括

4 設置單元格字體顏色、背景顏色和字體字符
  QTableWidgetItem *item = new QTableWidgetItem("ID");
  item->setBackgroundColor(QColor(0,60,10));
  item->setTextColor(QColor(200,111,100));
  item->setFont(QFont("Helvetica"));
  tableWidget->setItem(0,1,item);

5 設置單元格的大小
  //通過指定某個行或者列的大小
  tableWidget->setColumnWidth(3,200);
  tableWidget->setRowHeight(3,60);

  //設置為由內容決定
  tableWidget->resizeColumnsToContents();
  tableWidget->resizeRowsToContents();


6 清除表格數據
  tableWidget->clear(); //清除所有可見數據(包括表頭),行還在
  tableWidget->clearContents(); //只清除表中數據,不清除表頭內容
  tableWidget->setRowCount(0); //連行也清除掉

7 獲取/添加/清除行數據
  //獲取選中表格的行號
  int row = tableWidget->currentItem()->row();

  //獲取表格中當前總行數
  int row = tableWidget->rowCount();

  //添加一行
  tableWidget->setRowCount(row+1);

  //清除row行
  tableWidget->removeRow(row);


8 注意事項1
  在使用on_tableWidget_currentCellChanged槽函數時需要注意負值的判斷,
  否則在使用clear()或clearContents()時進行刪除表格數據時會調用此函數而使得程序異常
  void CAN_Demo::on_tableWidget_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
  {
    // cout << currentRow << currentColumn;
    // cout << previousRow << previousColumn;
    // Q_UNUSED(currentColumn);
    Q_UNUSED(previousRow); //初始化表格后的值為-1
    Q_UNUSED(previousColumn); //初始化表格后的值為-1

    //要增加功能檢測
    if(currentRow < 0 || currentColumn < 0)
    {
      return;
    }
    ... //功能實現
  }

參考鏈接:https://www.cnblogs.com/aiguona/p/10400111.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM