我已使用QTableview
和QAbstractTableModel
創建了一個表。在最後一列中,我也能夠爲每一行添加一個按鈕(該單元格的右下角)。現在我想自定義它的風格,比如將背景顏色更改爲黑色,邊框等。將自定義樣式添加到QTableview中添加的按鈕
有沒有什麼辦法可以實現這一點?
我已使用QTableview
和QAbstractTableModel
創建了一個表。在最後一列中,我也能夠爲每一行添加一個按鈕(該單元格的右下角)。現在我想自定義它的風格,比如將背景顏色更改爲黑色,邊框等。將自定義樣式添加到QTableview中添加的按鈕
有沒有什麼辦法可以實現這一點?
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(); }
嗨tanmayb,你發佈了一個答案,看起來像你的問題的補充。如果是,請編輯您的問題並刪除「答案」。 – bummi
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;"
"}");
你確定嗎? 它可能會改變所有的tableviews風格,而不僅僅是按鈕。 – tanmayb
查看第一個鏈接部分帶有'後代選擇器'的選擇器類型'表格行。所以這應該隻影響表格視圖中的按鈕。沒有測試它,但它應該工作。 –
這將是最好的,如果你只是嘗試它。 AFAIK樣式表有時會產生不必要的副作用,這取決於您使用的樣式(這通常取決於平臺)。 –
你怎麼添加按鈕? –