2017-08-22 204 views
0

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

有没有什么办法可以实现这一点?

+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(); } 
+0

嗨tanmayb,你发布了一个答案,看起来像你的问题的补充。如果是,请编辑您的问题并删除“答案”。 – bummi

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;" 
    "}"); 
+0

你确定吗? 它可能会改变所有的tableviews风格,而不仅仅是按钮。 – tanmayb

+0

查看第一个链接部分带有'后代选择器'的选择器类型'表格行。所以这应该只影响表格视图中的按钮。没有测试它,但它应该工作。 –

+0

这将是最好的,如果你只是尝试它。 AFAIK样式表有时会产生不必要的副作用,这取决于您使用的样式(这通常取决于平台)。 –

相关问题