Qt/Images/SemiTransparentPixels
From ProgrammingExamples
main.cpp
#include <QApplication> #include "form.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Form form; form.show(); return app.exec(); }
form.h
#ifndef FORM_H #define FORM_H #include "ui_form.h" class Form : public QWidget, private Ui::Form { Q_OBJECT public: Form(QWidget *parent = 0); }; #endif
form.cpp
#include <QtGui> #include <QGraphicsScene> #include <QGraphicsView> #include <QPixmap> #include "form.h" Form::Form(QWidget *parent) : QWidget(parent) { setupUi(this); QPixmap pixmap(100,100); //QColor black(0,0,0); QColor red(255,0,0); pixmap.fill(red); QPixmap alpha(100,100); QPainter painter( &alpha); // Set everything to opaque red painter.setPen(QColor( 255, 0, 0, 255 )); for(unsigned int i = 0; i < 100; ++i) { for(unsigned int j = 0; j < 100; ++j) { painter.drawPoint(i, j); } } // Set the top left corner to totally transparent painter.setPen(QColor( 255, 0, 0, 0 )); for(unsigned int i = 0; i < 50; ++i) { for(unsigned int j = 0; j < 50; ++j) { painter.drawPoint(i, j); } } // Set the top right corner to semi-transparent red painter.setPen( QColor( 255, 0, 0, 127 ) ); for(unsigned int i = 50; i < 100; ++i) { for(unsigned int j = 0; j < 50; ++j) { painter.drawPoint(i, j); } } // A pixel value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0 means the pixel is transparent. pixmap.setAlphaChannel(alpha); //pixmap.setMask(alpha); QGraphicsScene* scene = new QGraphicsScene; scene->addPixmap(pixmap); this->graphicsView->setScene(scene); }
form.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>Form</class> <widget class="QWidget" name="Form"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>400</width> <height>300</height> </rect> </property> <property name="windowTitle"> <string>Form</string> </property> <widget class="QGraphicsView" name="graphicsView"> <property name="geometry"> <rect> <x>60</x> <y>50</y> <width>256</width> <height>192</height> </rect> </property> </widget> </widget> <resources/> <connections/> </ui>
CMakeLists.txt
cmake_minimum_required(VERSION 2.6) PROJECT(QPixmapOpacity) FIND_PACKAGE(Qt4 REQUIRED) INCLUDE(${QT_USE_FILE}) QT4_WRAP_UI(UISrcs form.ui) QT4_WRAP_CPP(MOCSrcs form.h) include_directories(${include_directories} ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) ADD_EXECUTABLE(QPixmapOpacity main.cpp form.h form.cpp ${MOCSrcs} ${UISrcs}) TARGET_LINK_LIBRARIES(QPixmapOpacity ${QT_LIBRARIES})