File indexing completed on 2024-05-19 05:42:25
0001 // ct_lvtqtw_backgroundeventfilter.cpp -*-C++-*- 0002 0003 /* 0004 // Copyright 2023 Codethink Ltd <codethink@codethink.co.uk> 0005 // SPDX-License-Identifier: Apache-2.0 0006 // 0007 // Licensed under the Apache License, Version 2.0 (the "License"); 0008 // you may not use this file except in compliance with the License. 0009 // You may obtain a copy of the License at 0010 // 0011 // http://www.apache.org/licenses/LICENSE-2.0 0012 // 0013 // Unless required by applicable law or agreed to in writing, software 0014 // distributed under the License is distributed on an "AS IS" BASIS, 0015 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 0016 // See the License for the specific language governing permissions and 0017 // limitations under the License. 0018 */ 0019 0020 #include <ct_lvtqtw_backgroundeventfilter.h> 0021 0022 #include <QAbstractItemModel> 0023 #include <QAbstractItemView> 0024 #include <QBrush> 0025 #include <QDebug> 0026 #include <QEvent> 0027 #include <QFontMetrics> 0028 #include <QPaintEvent> 0029 #include <QPainter> 0030 #include <QPen> 0031 0032 namespace Codethink::lvtqtw { 0033 0034 struct BackgroundEventFilter::Private { 0035 QString backgroundString; 0036 }; 0037 0038 BackgroundEventFilter::BackgroundEventFilter(QObject *parent): 0039 QObject(parent), d(std::make_unique<BackgroundEventFilter::Private>()) 0040 { 0041 } 0042 0043 BackgroundEventFilter::~BackgroundEventFilter() = default; 0044 0045 void BackgroundEventFilter::setBackgroundText(const QString& bgString) 0046 { 0047 d->backgroundString = bgString; 0048 } 0049 0050 bool BackgroundEventFilter::eventFilter(QObject *obj, QEvent *ev) 0051 { 0052 if (d->backgroundString.isEmpty()) { 0053 return false; 0054 } 0055 0056 if (!obj || !ev) { 0057 return false; 0058 } 0059 0060 auto *view = qobject_cast<QWidget *>(obj); 0061 if (!view) { 0062 return false; 0063 } 0064 0065 auto *viewParent = qobject_cast<QAbstractItemView *>(view->parentWidget()); 0066 if (!viewParent) { 0067 return false; 0068 } 0069 0070 if (ev->type() != QEvent::Paint) { 0071 if (ev->type() == QEvent::EnabledChange) { 0072 view->update(); 0073 return false; 0074 } 0075 return false; 0076 } 0077 0078 auto *model = viewParent->model(); 0079 if (!model) { 0080 return false; 0081 } 0082 0083 if (model->rowCount() != 0) { 0084 return false; 0085 } 0086 0087 QFontMetrics fm(view->font()); 0088 const int width = fm.horizontalAdvance(d->backgroundString); 0089 const int height = fm.height(); 0090 const int xPos = (view->width() / 2) - (width / 2); 0091 const int yPos = (view->height() / 2) - (height / 2); 0092 0093 QPainter painter; 0094 painter.begin(view); 0095 painter.setPen(QPen(QBrush(Qt::gray), 2)); 0096 painter.drawText(xPos, yPos, d->backgroundString); 0097 painter.end(); 0098 0099 return true; 0100 } 0101 0102 } // namespace Codethink::lvtqtw