Qt4 设置QTableWidget鼠标滑过的颜色

这是一个简单demo,直接贴代码。


tablewidget.h

#ifndef TABLEWIDGET_H
#define TABLEWIDGET_H

#include <QTableWidget>
#include <QEvent>

class TableWidget : public QTableWidget
{
    Q_OBJECT
public:
    explicit TableWidget(QWidget *parent = 0);

protected:
    void setRowColor(int row, QColor color);
    
signals:
    
public slots:
    void mycellEntered(int row, int column);

private:
    QTableWidget *tableWidget;
    QColor defaultBkColor;
    int previousColorRow;
};

#endif // TABLEWIDGET_H

tablewidget.cpp

#include "tablewidget.h"
#include <QMessageBox>
#include <QPoint>

TableWidget::TableWidget(QWidget *parent) :
    QTableWidget(parent)
{
    setGeometry(100,100,600,300);
    defaultBkColor = QColor(255,255,255);   //默认背景色
    previousColorRow = -1;

    tableWidget = new QTableWidget(this);
    tableWidget->setRowCount(10);   //设置行数为10
    tableWidget->setColumnCount(5); //设置列数为5
    tableWidget->setGeometry(10,10,580,280);

    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);   //设置整行选择
    tableWidget->setMouseTracking(true);    //开启捕获鼠标功能
    tableWidget->setStyleSheet("selection-background-color:pink");  //设置选中行颜色
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);    //禁止编辑表格

    for (int i=0; i<10; i++)
        for (int j=0; j<5;j++)
        {
            QTableWidgetItem *item = new QTableWidgetItem(QIcon(":/btn1_bright"), "Jan");
            tableWidget->setItem(i,j,item);
        }

    connect(tableWidget,SIGNAL(cellEntered(int,int)),this,SLOT(mycellEntered(int,int)));
}

void TableWidget::mycellEntered(int row, int column)
{
    QTableWidgetItem *item = 0;

    //还原上一行的颜色
    item = tableWidget->item(previousColorRow, 0);
    if (item != 0)
    {
        this->setRowColor(previousColorRow, defaultBkColor);
    }

    //设置当前行的颜色
    item = tableWidget->item(row, column);
    if (item != 0 && !item->isSelected() && !item->text().isEmpty())
    {
        this->setRowColor(row, QColor(193,210,240));
    }

    //设置行的索引
    previousColorRow = row;
}

//设置某一行的颜色
void TableWidget::setRowColor(int row, QColor color)
{
    for (int col=0; col<tableWidget->columnCount(); col++)
    {
        QTableWidgetItem *item = tableWidget->item(row, col);
        item->setBackgroundColor(color);
    }
}

main.cpp

#include <QApplication>
#include <QTextCodec>
#include "tablewidget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec::setCodecForTr(QTextCodec::codecForName("System"));  //消除乱码

    TableWidget tableWidget;
    tableWidget.show();

    return a.exec();
}
运行效果:

Qt4 设置QTableWidget鼠标滑过的颜色_第1张图片


你可能感兴趣的:(Qt4 设置QTableWidget鼠标滑过的颜色)