Reputation: 2363
I'm trying to set a QPdfView's viewport
background color, but unlike QAbstractScrollArea
(from which QPdfView
's derived), using stylesheet does not work.
Here's how I tried to do that:
#include <QApplication>
#include <QPdfView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QPdfView *pdfView = new QPdfView();
pdfView->setMinimumSize(100,100);
//I tried to set stylesheet in different ways, in multiple combinations
//but none worked
//pdfView->setStyleSheet("background: white");
pdfView->setStyleSheet("QWidget{background: white;}");
//pdfView->viewport()->setStyleSheet("background: white");
pdfView->show();
return a.exec();
}
Note: You need to to find and target PdfWidgets
, so modify your CMakeLists.txt
according the below, to be able to use QPdfView
:
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets PdfWidgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets PdfWidgets)
target_link_libraries(MyExperiments PRIVATE
Qt${QT_VERSION_MAJOR}::Widgets
Qt${QT_VERSION_MAJOR}::PdfWidgets)
Here's how it looks, viewport
is grey, and you can see the white background of QPdfView
on the borders:
I also tried to change the background color of viewport
by overriding QAbstractScrollArea::paintEvent, and here's how:
void paintEvent(QPaintEvent *event)
{
QPdfView::paintEvent(event);
QPainter p(viewport());
QRect rect = viewport()->rect();
rect.adjust(-1,-1,0,0);
p.setBrush(QBrush(QColor(0,0,100)));
p.drawRect(rect);
}
But that ended up painting over viewport
, not changing its background color, so it covers open documents, because If I use a transparent color, I can see the document through it.
I'm open to either or other ways, but I'd like to avoid using paintEvent
if possible.
Upvotes: 2
Views: 391
Reputation: 2363
If you look at QPdfView's source code of paintEvent
, you'll notice QPalette::Dark being used to fill viewport
, and based on that, you can change its background color without obscuring open documents as follows:
#include <QApplication>
#include <QPdfView>
#include <QPalette>
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QPdfView view;
QPalette palette = view.palette();
palette.setBrush(QPalette::Dark, QColor("lime"));
view.setPalette(palette);
view.show();
return app.exec();
}
Note: QPalette::Dark
needs to be used, changes to painting the viewport will only occur if made through it.
Source: Qt Forum How to set QPdfView's viewport background color?
Credit: ChrisW67
Upvotes: 1