将自定义样式添加到 QTableview 中添加的按钮
Adding custom style to button added in QTableview
我使用QTableview
和QAbstractTableModel
创建了一个表。在最后一列中,我还能够为每一行(该单元格的右上角(添加一个按钮。现在我想自定义它的样式,比如将背景颜色更改为黑色、边框等。
有什么办法可以做到这一点吗?
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); };
代表.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();
}
} }
主.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(); }
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;"
"}");
相关文章:
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 按下时将图像添加到按钮
- 将自定义样式添加到 QTableview 中添加的按钮
- 隐藏、显示、添加或删除功能区中的按钮?
- 添加按钮以通知运行函数的通知
- 添加按钮时出错,即使存在这样的插槽,也不存在
- 如何将按钮添加到节点的属性编辑器面板,该面板调用该节点内的方法?
- 如何使用 GTK 将图像添加到按钮
- 从代码添加时无法单击Qt按钮
- 我动态添加一个按钮,如何在Qt的另一个空白中使用此按钮
- 将自定义按钮标题添加到消息框
- 如何添加C++/WinRT按钮单击处理程序
- 如何使用C++代码并将其添加到 C# gui 按钮
- 如何使用GTKMM添加对按钮的响应
- 如何在橘子酱工具的UI中添加按钮
- 如何在QTreeWidget Header中添加按钮或其他小部件
- 如何存储数据,并在firefox / chrome javascript插件中添加按钮
- 想要在setTimer和setText中添加按钮
- 在DOS中添加按钮
- 向标题栏添加按钮