Qt/Images/SemiTransparentPixels

From ProgrammingExamples
< Qt
Revision as of 20:42, 14 November 2011 by Daviddoria (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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(255,0,0);
  pixmap.fill(black);
 
  QBitmap alpha(100,100);
  QPainter painter( &alpha); 
 
  // Set everything to opaque
  painter.setPen(Qt::color0);
  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 transparent
  painter.setPen(Qt::color1);
  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
  painter.setPen(.5);
  for(unsigned int i = 51; 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);
 
  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})