将自定义样式添加到QTableview中添加的按钮

时间:2017-08-22 08:23:50

标签: c++ qt qt4

我使用QTableviewQAbstractTableModel创建了一个表格。在最后一列中,我还可以为每一行(该单元格的右角)添加一个按钮。现在我想自定义它的样式,比如将背景颜色改为黑色,边框等。

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:0)

delegate.h:

class MyDelegate : public QItemDelegate {
    Q_OBJECT

public:
    MyDelegate(QObject *parent = 0);
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); };

delegate.cpp:

 #include <QtGui>  #include "delegate.h"

 MyDelegate::MyDelegate(QObject *parent)
     : QItemDelegate(parent)  {  }


 void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const  {
     QStyleOptionButton button;
     QRect r = option.rect;//getting the rect of the cell
     int x,y,w,h;
     x = r.left() + r.width() - 30;//the X coordinate
     y = r.top();//the Y coordinate
     w = 30;//button width
     h = 30;//button height
     button.rect = QRect(x,y,w,h);
     button.text = "=^.^=";
     button.state = QStyle::State_Enabled;

     QApplication::style()->drawControl( QStyle::CE_PushButton, &button, painter);  }

 bool MyDelegate::editorEvent(QEvent *event, QAbstractItemModel
*model, const QStyleOptionViewItem &option, const QModelIndex &index)  {
     if( event->type() == QEvent::MouseButtonRelease )
     {
         QMouseEvent * e = (QMouseEvent *)event;
         int clickX = e->x();
         int clickY = e->y();

         QRect r = option.rect;//getting the rect of the cell
         int x,y,w,h;
         x = r.left() + r.width() - 30;//the X coordinate
         y = r.top();//the Y coordinate
         w = 30;//button width
         h = 30;//button height

         if( clickX > x && clickX < x + w )
             if( clickY > y && clickY < y + h )
             {
                 QDialog * d = new QDialog();
                 d->setGeometry(0,0,100,100);
                 d->show();
             }
     }  }

的main.cpp

#include "delegate.h"

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QStandardItemModel model(4, 2);
    QTableView tableView;
    tableView.setModel(&model);

    MyDelegate delegate;
    tableView.setItemDelegate(&delegate);

    tableView.horizontalHeader()->setStretchLastSection(true);
    tableView.show();
    return app.exec(); }

答案 1 :(得分:0)

IMO最好的方法是使用样式表。 http://doc.qt.io/qt-5/stylesheet-syntax.html http://doc.qt.io/qt-5/stylesheet-reference.html

qApp->setStylSheet("QTableview QPushButton {" // apply only on push buttons inside a table view
    "    background-color: red;"
    "    border-style: outset;"
    "    border-width: 2px;"
    "    border-color: beige;"
    "}");
相关问题