Qt QTableWidget的用法


简述:

表格类是Qt中常用的控件,如QTableWidget,QTableViewQTableWidget是QTableView的子类,主要区别是QTableView可以使用自定义的数据模型来显示内容(即先通过setModel来绑定数据源),而QTableWidget则只能使用标准的数据模型,并且其单元格数据是QTableWidgetItem的对象来实现的(即无需要数据源,逐个单元格信息填好即可)。QTableWidgetItem用来表示表格中的一个单元格,整个QTableWidget表格都需要用逐个单元格构建起来.


1、QTableWidget的基本用法


#include "tabletab.h"
#include "common.h"
#include 
#include 
#include 
#include 
#include 
TableTab::TableTab(QWidget *parent) : QWidget(parent)
{    
    createUi();
    refreshLanguage();
    setAttribute (Qt::WA_DeleteOnClose);  
}
void TableTab::createUi()
{
    m_row = 21;
    m_column = 11;
    QVBoxLayout *b_vMainLayout = new QVBoxLayout();
    QHBoxLayout *b_hBtnLayout = new QHBoxLayout();
    m_pViewerTable = new QTableWidget(m_row,m_column);
    m_pClearBtn = new QPushButton();
    m_pCopyBtn = new QPushButton();
    m_pTimeLabel = new QLabel();
    m_pTimeValue = new QLabel();
    m_pClearBtn->setIcon(QIcon(g_imgPath + "/clear.png"));
    m_pCopyBtn->setIcon(QIcon(g_imgPath + "/copy.png"));
    m_pClearBtn->setFlat(true);
    m_pCopyBtn->setFlat(true);
//    m_pViewerTable->horizontalHeader()->setStretchLastSection(true); //自动调整最后一列的宽度使它和表格的右边界对齐
    m_pViewerTable->setEditTriggers(QAbstractItemView::NoEditTriggers); //设置为不可编辑方式
//    m_pViewerTable->setColumnWidth(0,135); //设置列宽度
//    m_pViewerTable->horizontalHeader()->setVisible(false); //隐藏列表头
    m_pViewerTable->verticalHeader()->setVisible(false); //隐藏行表头
    m_pViewerTable->setSelectionBehavior(QAbstractItemView::SelectItems);   // 单个选中
//    m_pViewerTable->setSelectionBehavior(QAbstractItemView::SelectRows);    // 整行选择
    m_pViewerTable->setSelectionMode(QAbstractItemView::ExtendedSelection);  // 可以选中多个
//    m_pViewerTable->setStyleSheet("selection-background-color:pink"); //选中颜色
    for(int row = 0; row < m_row;row++)
    {
        QTableWidgetItem *item0, *item1;
        item0 = new QTableWidgetItem;
        item1 = new QTableWidgetItem;
        item0->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);  //居中
        item1->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        QString txt = QString("%1").arg(row + 1);
        item0->setText(txt);
        m_pViewerTable->setItem(row, 0, item0);
        txt = QString("%1").arg((row + 1) * 2);
        item1->setText(txt);
        m_pViewerTable->setItem(row, 1, item1);
    }
    QWidget *spacer = new QWidget(this);
    spacer->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    b_hBtnLayout->addWidget(m_pTimeLabel);
    b_hBtnLayout->addWidget(m_pTimeValue);
    b_hBtnLayout->addWidget(spacer);
    b_hBtnLayout->addWidget(m_pClearBtn);
    b_hBtnLayout->addWidget(m_pCopyBtn);
    b_hBtnLayout->setSpacing(0);  //0 //设置间距
    b_vMainLayout->addLayout(b_hBtnLayout);
    b_vMainLayout->addWidget(m_pViewerTable);
    this->setLayout(b_vMainLayout);
}
void TableTab::refreshLanguage()
{
    m_viewerHeader<setHorizontalHeaderLabels(m_viewerHeader);
    m_pTimeLabel->setText(tr("Time:"));
}

 
   
 
   

Qt QTableWidget的用法_第1张图片

2、详解

#include 
#include 
#include 


1> 新建表格/设置行数/设置列数

    QTableWidget *m_pViewerTable = new QTableWidget(m_row,m_column);   
    m_pViewerTable->setRowCount(m_row);   //设置行数为m_row  
    m_pViewerTable->setColumnCount(m_column); //设置列数为m_column 

2> 设置行标题及对齐方式/设置列标题

    //设置表格行表头  
    QStringList headerLabels;  
    headerLabels << "Step" << "Range 0";  
    m_pViewerTable->setHorizontalHeaderLabels(headerLabels);  
           
    //设置表格行标题的对齐方式  
    m_pViewerTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);  
      
    //设置列表头  
    QStringList rowLabels;  
    rowLabels << "row 1" << "row 2" << "row 3" << "row 4";  
    m_pViewerTable->setVerticalHeaderLabels(rowLabels);  

3> 隐藏行/列标题

    //隐藏列表头
    m_pViewerTable->horizontalHeader()->setVisible(false); 
    //隐藏行表头
    m_pViewerTable->verticalHeader()->setVisible(false); 


4> 设置行高度/列宽度

    //设置第0行的高度  
    m_pViewerTable->setRowHeight(0, 122);  
    //设置第0列宽度
    m_pViewerTable->setColumnWidth(0,135); 

将行和列的大小设为与内容相配:

    m_pViewerTable->resizeColumnsToContents();  
    m_pViewerTable->resizeRowsToContents();  


5> 自动调整最后一列的宽度使它和表格的右边界对齐

    //自动调整最后一列的宽度使它和表格的右边界对齐
    m_pViewerTable->horizontalHeader()->setStretchLastSection(true);   // #include 

6> 设置表格选择方式

    // 选中单个单元格
    m_pViewerTable->setSelectionBehavior(QAbstractItemView::SelectItems); 
    // 选中一行
    m_pViewerTable->setSelectionBehavior(QAbstractItemView::SelectRows); 
    // 选中一列
    m_pViewerTable->setSelectionBehavior(QAbstractItemView::SelectColumns); 

7> 单个/多个选中设置

    // 不能选择
    m_pViewerTable->setSelectionMode(QAbstractItemView::NoSelection);  
    // 选中单个目标
    m_pViewerTable->setSelectionMode(QAbstractItemView::SingleSelection);
    // 选中多个目标
    m_pViewerTable->setSelectionMode(QAbstractItemView::MultiSelection);
    // 正常情况下是单选,按下Ctrl键后,可以多选
    m_pViewerTable->setSelectionMode(QAbstractItemView::ExtendedSelection);
    // 正常情况下是单选,按下Shift键后,可以多选
    m_pViewerTable->setSelectionMode(QAbstractItemView::ContiguousSelection);


8> 设置编辑方式

    //不能对表格内容进行修改
    m_pViewerTable->setEditTriggers(QAbstractItemView::NoEditTriggers); 
    //任何时候都能对单元格修改
    m_pViewerTable->setEditTriggers(QAbstractItemView::CurrentChanged); 
    //双击单元格
    m_pViewerTable->setEditTriggers(QAbstractItemView::DoubleClicked); 
    //单击已选中的内容
    m_pViewerTable->setEditTriggers(QAbstractItemView::SelectedClicked); 
    //按下Edit键修改
    m_pViewerTable->setEditTriggers(QAbstractItemView::EditKeyPressed);
    //按下任意键就能修改
    m_pViewerTable->setEditTriggers(QAbstractItemView::AnyKeyPressed); 
    //以上条件全包括
    m_pViewerTable->setEditTriggers(QAbstractItemView::AllEditTriggers); 

9> 设置单元格内容/对齐方式

//设置单元格内容

void QTableWidget::setItem(int row, int column, QTableWidgetItem * item)

每个单元格都有一个自己的item,不能共用。


    //居中对齐
    item0->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter); 


Qt QTableWidget的用法_第2张图片


Qt QTableWidget的用法_第3张图片


10>  设置选中颜色

    //设置选中颜色
    m_pViewerTable->setStyleSheet("selection-background-color:pink"); 

11> 设置单元格字体颜色和背景颜色及字体字符

    QTableWidgetItem *item = new QTableWidgetItem("Apple");  
    item->setBackgroundColor(QColor(0,60,10));  
    item->setTextColor(QColor(200,111,100));  
    item->setFont(QFont("Helvetica"));  
    m_pViewerTable->setItem(0,3,item);  

另:如果需要对所有的单元格都使用这种字体,则可以使用:

m_pViewerTable->setFont(QFont("Helvetica"));

合并单元格:

m_pViewerTable->setSpan(0, 0, 3, 1);

void QTableView::setSpan(int rowint columnint rowSpanCountint columnSpanCount);


12> 其他

    //清除已有的行列
    for(int i = m_pViewerTable->rowCount();i > 0;i--)
    {
        m_pViewerTable->removeRow(0);
    }
    //显示表格线
    m_pViewerTable->setShowGrid(true);
    //去掉水平滚动条
    m_pViewerTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    //垂直滚动条按项移动
    m_pViewerTable->setVerticalScrollMode(QAbstractItemView::ScrollPerItem);
    //去掉自动滚动
    m_pViewerTable->setAutoScroll(false);



13> 右键菜单实现


头文件:

private:
 
   
    QMenu *m_pPopMenu;
    QAction *m_pCopyAct;
 
   
public slots:
    void on_customContextMenuRequested(QPoint pos); 
    void copyData();

cpp文件:

A. 构造函数

    /****
     * setContextMenuPolicy方法用来设置widget菜单项的显示方法,而CustomContextMenu是唯一与右键菜单
     * 有关的参数,因此这里我们将菜单显示方法设置为该类型。如果widget设置为CustomContextMenu时,
     * 当在数据上点击右键时就会发送customContextMenuRequested(const QPoint &pos)信号,
     * 该信号还会捕捉到点击右键的位置,并用pos参数来存储。
     *
    ****/
    m_pViewerTable->setContextMenuPolicy(Qt::CustomContextMenu);
    m_pPopMenu = new QMenu(m_pViewerTable);
    m_pCopyAct = new QAction("Copy",this);
    connect(m_pViewerTable, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(on_customContextMenuRequested(QPoint)));
    connect(m_pCopyAct, SIGNAL(triggered()),this,SLOT(copyData()));

B.两个槽函数


void TableTab::on_customContextMenuRequested(QPoint pos)
{
    m_pPopMenu->addAction(m_pCopyAct);
    m_pPopMenu->exec(QCursor::pos());
}


void TableTab::copyData()
{
    QList items = m_pViewerTable->selectedItems();
    int count = items.count();
    QString b_itemsStr;
    int b_preRow = 0;
    int b_curRow = 0;
    for(int i = 0;i < count;i++)
    {
        b_curRow = m_pViewerTable->row(items.at(i));//获取选中的行
        QTableWidgetItem *item = items.at(i);
//        if(i == 0){
//            b_preRow = b_curRow;
//        }
//        if(b_preRow != b_curRow){
//            b_preRow = b_curRow;
//            b_itemsStr += "\n";
//        }
//        b_itemsStr += item->text() + "\t";//获取内容

        if(i == 0) {
            b_preRow = b_curRow;
            b_itemsStr += item->text();//获取内容
            continue;
        }
        if(b_preRow != b_curRow) {
            b_preRow = b_curRow;
            b_itemsStr += "\n";
        } else {
            b_itemsStr += "\t";
        }
        b_itemsStr += item->text();//获取内容
    }

    QClipboard *clipboard = QApplication::clipboard();   //获取系统剪贴板指针
    clipboard->setText(b_itemsStr);                  //设置剪贴板内容
//    QString originalText = clipboard->text();         //获取剪贴板上文本信息

}


    QList  b_selectRanges = m_pViewerTable->selectedRanges();
    int b_rangesCount = b_selectRanges.count();  //选中区域的个数
    for(int i = 0;i < b_rangesCount;i++)
    {
        int topRow = b_selectRanges.at(i).topRow();
        int bottomRow = b_selectRanges.at(i).bottomRow();
        int leftColumn = b_selectRanges.at(i).leftColumn();
        int rightColumn = b_selectRanges.at(i).rightColumn();

        for(int j = topRow;j <= bottomRow;j++)
        {
            qDebug()<<"selectRow"<






http://blog.csdn.net/pigautumn/article/details/9013141

http://blog.csdn.net/qiao_yihan/article/details/46413345

http://blog.csdn.net/polokang/article/details/6696982

http://blog.csdn.net/xgbing/article/details/7774737



你可能感兴趣的:(Qt)