void MenuEquipmentScreen::initialize(BattleCharacterItem *character, Inventory *inventory) { QFont font("Times", 12, QFont::Bold); QBrush brush(Qt::white); _state = EQUIPPED_SELECTION; // Set character and inventory _character = character; _inventory = inventory; // Set the character's equipment QPointF position(_equippedEquipmentItem->pos().x(), _equippedEquipmentItem->pos().y() + 40); QStringList equipmentHeaders; equipmentHeaders << "Main Hand: " << "Off Hand: " << "Helmet: " << "Torso: " << "Leggings: " << "Gloves: " << "Boots: " << "Earring: " << "Necklace: " << "Ring: "; QVector<EquipmentPiece*> equipment = _character->getEquipment()->getEquipment(); _currentEquippedEquipmentPiece = equipment.at(0); _equippedEquipmentItem->setText("Equipment of " + _character->getName()); for (int i = 0; i < equipment.size(); i++) { QString itemText; itemText.append(equipmentHeaders.at(i)); if (!!equipment.at(i)) itemText.append(equipment.at(i)->getName()); QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(this); item->setText(itemText); item->setBrush(brush); item->setFont(font); item->setPos(position); _equippedEquipmentItems.append(item); position.setY(position.y() + 20); } setCurrentEquippedItem(_equippedEquipmentItems.at(0), equipment.at(0)); // Set Image if (_character->getCharacter()->getBattleImage().second != QString()) { QPixmap battlerImage = _character->getCharacter()->getBattleImage().first; if ((battlerImage.width() > _characterImage->boundingRect().width()) || (battlerImage.height() > _characterImage->boundingRect().height())) battlerImage = battlerImage.scaled(QSize(200, 200), Qt::KeepAspectRatio); QPixmap frame(200, 200); frame.fill(Qt::transparent); QPainter painter(&frame); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); QPoint position(0, 0); position.setX(frame.width()/2 - battlerImage.width()/2); position.setY(frame.height()/2 - battlerImage.height()/2); painter.drawPixmap(position, battlerImage); painter.end(); _characterImage->setPixmap(frame); } else { QPixmap image(200, 200); image.fill(Qt::transparent); _characterImage->setPixmap(image); } }
void MediaSourceDesktop::CreateScreenshot() { AVFrame *tRGBFrame; mMutexGrabberActive.lock(); if (!mMediaSourceOpened) { mMutexGrabberActive.unlock(); return; } if (mWidget == NULL) { LOG(LOG_ERROR, "Capture widget is invalid"); mMutexGrabberActive.unlock(); return; } QTime tCurrentTime = QTime::currentTime(); int tTimeDiff = mLastTimeGrabbed.msecsTo(tCurrentTime); //### skip capturing when we are too slow if (tTimeDiff < 1000 / (mFrameRate + 0.5 /* some tolerance! */)) { #ifdef MSD_DEBUG_PACKETS LOG(LOG_VERBOSE, "Screen capturing skipped because system is too fast"); #endif mMutexGrabberActive.unlock(); return; } if (mLastTimeGrabbed == QTime(0, 0, 0, 0)) { mLastTimeGrabbed = tCurrentTime; mMutexGrabberActive.unlock(); return; }else mLastTimeGrabbed = tCurrentTime; //### skip capturing when we are too slow if (tTimeDiff > 1000 / MIN_GRABBING_FPS) { LOG(LOG_WARN, "Screen capturing skipped because system is too busy"); mMutexGrabberActive.unlock(); return; } //#################################################################### //### do the grabbing and scaling stuff //#################################################################### QPixmap tSourcePixmap; // screen capturing #ifdef APPLE CGImageRef tOSXWindowImage = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, mWidget->winId(), kCGWindowImageDefault); tSourcePixmap = QPixmap::fromMacCGImageRef(tOSXWindowImage).copy(mGrabOffsetX, mGrabOffsetY, mSourceResX, mSourceResY); CGImageRelease(tOSXWindowImage); #else tSourcePixmap = QPixmap::grabWindow(mWidget->winId(), mGrabOffsetX, mGrabOffsetY, mSourceResX, mSourceResY); #endif if(!tSourcePixmap.isNull()) { // record screenshot via ffmpeg if (mRecording) { if ((tRGBFrame = AllocFrame()) == NULL) { LOG(LOG_ERROR, "Unable to allocate memory for RGB frame"); }else { QImage tSourceImage = QImage((unsigned char*)mOriginalScreenshot, mSourceResX, mSourceResY, QImage::Format_RGB32); QPainter *tSourcePainter = new QPainter(&tSourceImage); tSourcePainter->drawPixmap(0, 0, tSourcePixmap); delete tSourcePainter; // Assign appropriate parts of buffer to image planes in tRGBFrame FillFrame(tRGBFrame, mOriginalScreenshot, PIX_FMT_RGB32, mSourceResX, mSourceResY); // set frame number in corresponding entries within AVFrame structure tRGBFrame->pts = mRecorderChunkNumber; tRGBFrame->coded_picture_number = mRecorderChunkNumber; tRGBFrame->display_picture_number = mRecorderChunkNumber; mRecorderChunkNumber++; // emulate set FPS tRGBFrame->pts = FpsEmulationGetPts(); // re-encode the frame and write it to file RecordFrame(tRGBFrame); } } // get the scaled version of the capture screen segment QPixmap tTargetPixmap = tSourcePixmap.scaled(mTargetResX, mTargetResY); // lock screenshot buffer mMutexScreenshot.lock(); QImage tTargetImage = QImage((unsigned char*)mOutputScreenshot, mTargetResX, mTargetResY, QImage::Format_RGB32); QPainter *tTargetPainter = new QPainter(&tTargetImage); tTargetPainter->drawPixmap(0, 0, tTargetPixmap); delete tTargetPainter; mScreenshotUpdated = true; // notify consumer about new screenshot mWaitConditionScreenshotUpdated.wakeAll(); // unlock screenshot buffer again mMutexScreenshot.unlock(); }else LOG(LOG_ERROR, "Source pixmap is invalid"); mMutexGrabberActive.unlock(); }
void Scene::bgChange() { //A && D A = new Btn; QPixmap a; a.load(":/image/image/A.png"); a = a.scaled(150,150); A->setPixmap(a); A->setPos(180,280); addItem(A); D = new Btn; QPixmap d; d.load(":/image/image/D.png"); d = d.scaled(170,170); D->setPixmap(d); D->setPos(270,270); addItem(D); /*connect*/ dis = 0; /*change background*/ QImage bg; bg.load(":/image/image/7658225_656869.jpg"); bg = bg.scaled(610,410); this->setBackgroundBrush(bg); /*remove button*/ this->removeItem(btn_start); this->removeItem(btn_exit); /*rail picture setting*/ rail = new Rail(); QPixmap rl; rl.load(":/image/image/panel.png"); rl = rl.scaled(610,100); rail->setPixmap(rl); rail->setPos(0,170); addItem(rail); /*matong pic setting*/ matong = new Rail(); QPixmap mt; mt.load(":/image/image/toilet-toilet-bowl_small.png"); mt = mt.scaled(300,300); matong->setPixmap(mt); matong->setPos(-100,35); addItem(matong); /*back button setting*/ btn_back = new Btn(); QPixmap bk; bk.load(":/image/image/go.png"); bk = bk.scaled(90,90); btn_back->setPixmap(bk); btn_back->setPos(0,5); btn_back_w = 80; btn_back_h = 85; addItem(btn_back); /*labi*/ labi = new Rail(); QPixmap lb; lb.load(":/image/image/0.gif"); lb = lb.scaled(250,250); labi->setPixmap(lb); labi->setPos(450,40); addItem(labi); /*Score*/ score1 = new Score(); score1->setPos(420,35); addItem(score1); /*time count*/ mytime = new myTimer(); mytime->setPos(200,35); addItem(mytime); }
void KipiImageModel::slotThumbnailFromInterface(const KUrl& url, const QPixmap& pixmap) { kDebug()<<url<<pixmap.size(); if (pixmap.isNull()) return; const int effectiveSize = qMax(pixmap.size().width(), pixmap.size().height()); // find the item corresponding to the URL: const QModelIndex imageIndex = indexFromUrl(url); kDebug()<<url<<imageIndex.isValid(); if (imageIndex.isValid()) { // this is tricky: some kipi interfaces return pixmaps at the requested size, others do not. // therefore we check whether a pixmap of this size has been requested. If so, we send it on. // If a pixmap of this size has not been requested, we rescale it to fulfill all other requests. // index, size QList<QPair<int, int> > openRequests; for (int i=0; i<d->requestedPixmaps.count(); ++i) { if (d->requestedPixmaps.at(i).first==imageIndex) { const int requestedSize = d->requestedPixmaps.at(i).second; if (requestedSize==effectiveSize) { // match, send it out. d->requestedPixmaps.removeAt(i); kDebug()<<i; // save the pixmap: const QString itemKeyString = CacheKeyFromSizeAndUrl(effectiveSize, url); d->pixmapCache->insert(itemKeyString, pixmap); emit(signalThumbnailForIndexAvailable(imageIndex, pixmap)); return; } else { openRequests << QPair<int, int>(i, requestedSize); } } } // the pixmap was not requested at this size, fulfill all requests: for (int i=openRequests.count()-1; i>=0; --i) { const int targetSize = openRequests.at(i).second; d->requestedPixmaps.removeAt(openRequests.at(i).first); kDebug()<<i<<targetSize; QPixmap scaledPixmap = pixmap.scaled(targetSize, targetSize, Qt::KeepAspectRatio); // save the pixmap: const QString itemKeyString = CacheKeyFromSizeAndUrl(targetSize, url); d->pixmapCache->insert(itemKeyString, scaledPixmap); emit(signalThumbnailForIndexAvailable(imageIndex, scaledPixmap)); } } }
void ImageFileNameBrowserWidget::setImageFileName(const QString& s) { _displayW->setText(s); QPixmap p; p.load(QFileInfo(_defaultPath, s).absoluteFilePath()); _previewW->setPixmap(p.scaled(QSize(300, 300), Qt::KeepAspectRatio)); }
SeaScene::SeaScene(QObject *parent) : QGraphicsScene(parent) { setItemPointersNull(); paused_ = false; screenLitKeeper_.keepScreenLit(true); QSettings settings; //set background QPixmap waves (":/pix/meri.png"); waves.scaled(20,20); setBackgroundBrush(QBrush(waves)); //set random seed qsrand(QTime::currentTime().msec()+2); //+2 to avoid setting it to 1 //Setup level sets QList<Level> levelList; Level level1(5,10); levelList.append(level1); Level level2(5,10,2,50); levelList.append(level2); Level level3(5,15,2,50); levelList.append(level3); Level level4(5,15,4,50); levelList.append(level4); Level level5(5,15,5,100); levelList.append(level5); Levelset set ("Original",levelList); availableLevelsets_.append(set); //Create another set of levels and place it in the available levelsets list levelList.clear(); Level set2level1(8,15,4,50); levelList.append(set2level1); Level set2level2(8,20,4,50); levelList.append(set2level2); Level set2level3(8,20,5,80); levelList.append(set2level3); Level set2level4(8,20,6,120); levelList.append(set2level4); Level set2level5(8,25,8,150); levelList.append(set2level5); Levelset set2("Difficult",levelList); availableLevelsets_.append(set2); //Setup starting levelset QString levelname = settings.value("levelset","Original").toString(); bool found = false; foreach (Levelset levelset, availableLevelsets_) { if (levelset.getName() == levelname) { levelset_ = levelset; found = true; break; } } if (!found) //The last used level is not available { levelset_ = availableLevelsets_.value(0); } currentLevel_ = 0; totalScore_ = 0; connect(this,SIGNAL(allGhostsPicked()),this,SLOT(nextLevel())); pVibrateAction_ = new QAction(tr("Vibration effects"),this); pVibrateAction_->setCheckable(true); connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool))); pVibrateAction_->setChecked(settings.value("vibration",false).toBool()); pPauseAction_ = new QAction(tr("Pause"),this); pPauseAction_->setCheckable(true); connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool))); deviceLockPollTimer_.setInterval(20*60); connect(&deviceLockPollTimer_,SIGNAL(timeout()),this,SLOT(pollDeviceLocked())); deviceLockPollTimer_.start(); autopauseTimer.setSingleShot(true); autopauseTimer.setInterval(15*60*1000); connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(turnPauseOn())); }
/******************************************************************************************************** * SLOTs for Logo Download ******************************************************************************************************* */ void IRNowPlayingView::handleLogoDownloaded(IRQPreset* aPreset) { LOG_METHOD; if( EIdle == iLogoDownloadState ) { return; } if( NULL == aPreset ) { if( EDownloadLogo == iLogoDownloadState ) { iLogoNeedUpdate = false; #ifdef ADV_ENABLED QTimer::singleShot(1, this, SLOT(updateAdvImage())); #endif } #ifdef ADV_ENABLED else if( EDownLoadAdvImage == iLogoDownloadState ) { iAdvImageNeedUpdate = false; } #endif iLogoDownloadState = EIdle; return; } QPixmap logoPixmap; if( logoPixmap.loadFromData((const unsigned char*)aPreset->logoData.constData(), aPreset->logoData.size()) ) { if( EDownloadLogo == iLogoDownloadState ) { saveStationLogo(logoPixmap); QPixmap newLogoPixmap = logoPixmap.scaled(QSize(KNowPlayingLogoSize,KNowPlayingLogoSize),Qt::KeepAspectRatio); QIcon logoQIcon(newLogoPixmap); HbIcon logoHbIcon(logoQIcon); iStationLogo->setIcon(logoHbIcon); iPlayController->emitStationLogoUpdated(true); iLogoNeedUpdate = false; getViewManager()->saveScreenShot(); #ifdef ADV_ENABLED QTimer::singleShot(1, this, SLOT(updateAdvImage())); #endif } #ifdef ADV_ENABLED else if( EDownLoadAdvImage == iLogoDownloadState ) { QIcon logoQIcon(logoPixmap); HbIcon logoHbIcon(logoQIcon); iAdvImage->setIcon(logoHbIcon); iAdvUrl = iPlayController->getNowPlayingPreset()->advertisementUrl; iAdvImageNeedUpdate = false; } #endif } else { if( EDownloadLogo == iLogoDownloadState ) { iLogoNeedUpdate = false; #ifdef ADV_ENABLED QTimer::singleShot(1, this, SLOT(updateAdvImage())); #endif } #ifdef ADV_ENABLED else if( EDownLoadAdvImage == iLogoDownloadState ) { iAdvImageNeedUpdate = false; } #endif } iLogoDownloadState = EIdle; delete aPreset; aPreset = NULL; }
void MainWindow::showEvent(QShowEvent *) { if(check==1){ for(int i=0;i<itemList.size();++i){ } itemList.clear(); scene->removeItem(restart); scene->removeItem(exit); scene->addItem(birdtmp); scene->addItem(tool); itemList.clear(); //bird,obticle,target birdNumber=0; ScreenMode=0; checkBird23=0; target1->hit=0; // qDebug()<<x<<" hit=0 "<<y<<endl; } if(playtimes==0){ // Timer connect(&timer,SIGNAL(timeout()),this,SLOT(birdHit())); connect(&timer,SIGNAL(timeout()),this,SLOT(tick())); connect(this,SIGNAL(quitGame()),this,SLOT(QUITSLOT())); timer.start(100/6); } // Setting the QGraphicsScene scene = new QGraphicsScene(0,0,width(),ui->graphicsView->height()); ui->graphicsView->setScene(scene); QImage bg; bg.load(":/img/bg.jpg"); bg=bg.scaled(960,540); ui->graphicsView->scene()->setBackgroundBrush(bg); //bg-bird birdtmp=new QGraphicsPixmapItem(); QPixmap bir; bir.load(":/img/bird1.png"); bir=bir.scaled(50,50); birdtmp->setPixmap(bir); birdtmp->setPos(205,360); ui->graphicsView->scene()->addItem(birdtmp); //bg-tool tool=new QGraphicsPixmapItem(); QPixmap tol; tol.load(":/img/tool.png"); tol=tol.scaled(50,70); tool->setPixmap(tol); tool->setPos(210,380); ui->graphicsView->scene()->addItem(tool); //score score=new Score(); this->scene->addItem(score); //dot for(int i=0;i<15;++i){ dots[i]=new QGraphicsPixmapItem(); scene->addItem(dots[i]); } // Create world world = new b2World(b2Vec2(0.0f, -9.8f)); // Setting Size GameItem::setGlobalSize(QSizeF(32,18),size()); // qDebug()<<size().width()<<" "<<size().height()<<endl; // Create ground (You can edit here) land1=new Land(3,1.5,5,3,QPixmap(":/img/GROUND.png").scaled(225,height()/6.0),world,scene); itemList.push_back(land1); land2=new Land(25,1.5,20,3,QPixmap(":/img/GROUND.png").scaled(600,height()/6.0),world,scene); itemList.push_back(land2); //create target target1=new Target(20.2f,6.4f,0.1f,&timer,QPixmap(":/img/target1.png").scaled(40,40),world,scene); itemList.push_back(target1); target2=new Target(26.0f,5.8f,0.1f,&timer,QPixmap(":/img/target1.png").scaled(40,40),world,scene); itemList.push_back(target1); target3=new Target(22.0f,5.0f,0.1f,&timer,QPixmap(":/img/target2.png").scaled(40,40),world,scene); itemList.push_back(target1); target4=new Target(29.0f,5.0f,0.1f,&timer,QPixmap(":/img/target2.png").scaled(40,40),world,scene); itemList.push_back(target1); //create obticle createobticle(); }
void weatherwidget::setCurrentIcon(QString icon) { // set icon for current weather conditions if (icon == "partlysunny" || icon == "mostlycloudy" ) { if(clock->hour() < 5 || clock->hour() > 20) { QPixmap *partlyMoony = new QPixmap(":Images/weather-moony-few-clouds.png"); *partlyMoony = partlyMoony->scaled(72, 72, Qt::KeepAspectRatio); currentIcon->setPixmap(*partlyMoony); } else { QPixmap *partlySunny = new QPixmap(":Images/weather-few-clouds.png"); *partlySunny = partlySunny->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*partlySunny); } } else if (icon == "fog") { QPixmap *fog = new QPixmap(":Images/weather-fog.png"); *fog = fog->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*fog); } else if (icon == "hazy") { if(clock->hour() < 5 || clock->hour() > 20) { QPixmap *hazeyMoony = new QPixmap(":Images/weather-moony.png"); *hazeyMoony = hazeyMoony->scaled(72, 72, Qt::KeepAspectRatio); currentIcon->setPixmap(*hazeyMoony); } else { QPixmap *haze = new QPixmap(":Images/weather-haze.png"); *haze = haze->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*haze); } } else if (icon == "cloudy") { QPixmap *cloudy = new QPixmap(":Images/weather-overcast.png"); *cloudy = cloudy->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*cloudy); } else if (icon == "rain" || icon == "chancerain") { QPixmap *showers = new QPixmap(":Images/weather-showers.png"); *showers = showers->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*showers); } else if (icon == "sleet" || icon == "chancesleet") { QPixmap *sleet = new QPixmap(":Images/weather-sleet.png"); *sleet = sleet->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*sleet); } else if (icon == "flurries" || icon == "snow" || icon == "chanceflurries" || icon == "chancesnow") { QPixmap *snow = new QPixmap(":Images/weather-snow.png"); *snow = snow->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*snow); } else if (icon == "clear" || icon == "sunny") { if(clock->hour() < 5 || clock->hour() > 20) { QPixmap *moony = new QPixmap(":Images/weather-moony.png"); *moony = moony->scaled(72, 72, Qt::KeepAspectRatio); currentIcon->setPixmap(*moony); } else { QPixmap *sunny = new QPixmap(":Images/weather-sunny.png"); *sunny = sunny->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*sunny); } } else if (icon == "mostlysunny" || icon == "partlycloudy" || icon == "unknown") { if(clock->hour() < 5 || clock->hour() > 20) { QPixmap *partlyCloudy = new QPixmap(":Images/weather-moony-very-few-clouds"); *partlyCloudy = partlyCloudy->scaled(72, 72, Qt::KeepAspectRatio); currentIcon->setPixmap(*partlyCloudy); } else { QPixmap *partlyCloudy = new QPixmap(":Images/weather-sunny-very-few-clouds.png"); *partlyCloudy = partlyCloudy->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*partlyCloudy); } } else if (icon == "tstorms" || icon == "chancetstorms") { QPixmap *thundershower = new QPixmap(":Images/weather-thundershower.png"); *thundershower = thundershower->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*thundershower); } }
// titleAddText needs to be const char* for tr() NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *_titleAddText): appName(_appName), titleAddText(qApp->translate("SplashScreen", _titleAddText)) { // load pixmap QPixmap pixmap; if (std::char_traits<char>::length(_titleAddText) == 0) { pixmap.load(":/icons/bitcoin"); } else { pixmap.load(":/icons/shillingcoin_splash"); } if(iconColorHueShift != 0 && iconColorSaturationReduction != 0) { // generate QImage from QPixmap QImage img = pixmap.toImage(); int h,s,l,a; // traverse though lines for(int y=0;y<img.height();y++) { QRgb *scL = reinterpret_cast< QRgb *>( img.scanLine( y ) ); // loop through pixels for(int x=0;x<img.width();x++) { // preserve alpha because QColor::getHsl doesn't return the alpha value a = qAlpha(scL[x]); QColor col(scL[x]); // get hue value col.getHsl(&h,&s,&l); // rotate color on RGB color circle // 70° should end up with the typical "testnet" green h+=iconColorHueShift; // change saturation value if(s>iconColorSaturationReduction) { s -= iconColorSaturationReduction; } col.setHsl(h,s,l,a); // set the pixel scL[x] = col.rgba(); } } //convert back to QPixmap #if QT_VERSION >= 0x040700 pixmap.convertFromImage(img); #else pixmap = QPixmap::fromImage(img); #endif } appIcon = QIcon(pixmap); trayAndWindowIcon = QIcon(pixmap.scaled(QSize(256,256))); }
void ProductDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { //painting background when selected... //QPalette::ColorGroup cg = option.state & QStyle::State_Enabled // ? QPalette::Normal : QPalette::Disabled; //Painting frame painter->setRenderHint(QPainter::Antialiasing); QString pixName = KStandardDirs::locate("appdata", "images/itemBox.png"); painter->drawPixmap(option.rect.x()+5,option.rect.y()+5, QPixmap(pixName)); //get item data const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex nameIndex = model->index(row, 1); QString name = model->data(nameIndex, Qt::DisplayRole).toString(); QByteArray pixData = model->data(index, Qt::DisplayRole).toByteArray(); nameIndex = model->index(row, 3); double stockqty = model->data(nameIndex, Qt::DisplayRole).toDouble(); nameIndex = model->index(row, 0); QString strCode = "# " + model->data(nameIndex, Qt::DisplayRole).toString(); //preparing photo to paint it... QPixmap pix; if (!pixData.isEmpty() or !pixData.isNull()) { pix.loadFromData(pixData); } else { pix = QPixmap(DesktopIcon("lemon-box", 64)); } int max = 128; if ((pix.height() > max) || (pix.width() > max) ) { if (pix.height() == pix.width()) { pix = pix.scaled(QSize(max, max)); } else if (pix.height() > pix.width() ) { pix = pix.scaledToHeight(max); } else { pix = pix.scaledToWidth(max); } } int x = option.rect.x() + (option.rect.width()/2) - (pix.width()/2); int y = option.rect.y() + (option.rect.height()/2) - (pix.height()/2) - 10; //painting photo if (!pix.isNull()) painter->drawPixmap(x,y, pix); //Painting name QFont font = QFont("Trebuchet MS", 10); font.setBold(true); //getting name size in pixels... QFontMetrics fm(font); int strSize = fm.width(name); int aproxPerChar = fm.width("A"); QString nameToDisplay = name; int boxSize = option.rect.width()-15; //minus margin and frame-lines if (strSize > boxSize) { int excess = strSize-boxSize; int charEx = (excess/aproxPerChar)+2; nameToDisplay = name.left(name.length()-charEx-7) +"..."; //qDebug()<<"Text does not fit, strSize="<<strSize<<" boxSize:" //<<boxSize<<" excess="<<excess<<" charEx="<<charEx<<"nameToDisplay="<<nameToDisplay; } painter->setFont(font); if (option.state & QStyle::State_Selected) { painter->setPen(Qt::yellow); painter->drawText(option.rect.x()+10,option.rect.y()+145, 150,20, Qt::AlignCenter, nameToDisplay); } else { painter->setPen(Qt::white); painter->drawText(option.rect.x()+10,option.rect.y()+145, 150,20, Qt::AlignCenter, nameToDisplay); } //painting stock Availability if (stockqty <= 0) { font = QFont("Trebuchet MS", 12); font.setBold(true); font.setItalic(true); painter->setFont(font); painter->setBackgroundMode(Qt::OpaqueMode); painter->setPen(Qt::red); painter->setBackground(QColor(255,225,0,160)); QString naStr = i18n(" Out of stock "); painter->drawText(option.rect.x()+10, option.rect.y()+(option.rect.height()/2)-10, 150, 20, Qt::AlignCenter, naStr); painter->setBackgroundMode(Qt::TransparentMode); } //painting code number font = QFont("Trebuchet MS", 9); font.setBold(false); font.setItalic(true); painter->setFont(font); painter->setBackgroundMode(Qt::TransparentMode); painter->setPen(Qt::white); painter->setBackground(QColor(255,225,0,160)); painter->drawText(option.rect.x()+10, option.rect.y()+5, 150, 20, Qt::AlignCenter, strCode); painter->setBackgroundMode(Qt::TransparentMode); }
QVariant Util::decorationForVariant(const QVariant &value) { switch (value.type()) { case QVariant::Brush: { const QBrush b = value.value<QBrush>(); if (b.style() != Qt::NoBrush) { QPixmap p(16, 16); p.fill(QColor(0, 0, 0, 0)); QPainter painter(&p); painter.setBrush(b); painter.drawRect(0, 0, p.width() - 1, p.height() - 1); return p; } } case QVariant::Color: { const QColor c = value.value<QColor>(); if (c.isValid()) { QPixmap p(16, 16); QPainter painter(&p); painter.setBrush(QBrush(c)); painter.drawRect(0, 0, p.width() - 1, p.height() - 1); return p; } } case QVariant::Cursor: { const QCursor c = value.value<QCursor>(); if (!c.pixmap().isNull()) { return c.pixmap().scaled(16, 16, Qt::KeepAspectRatio, Qt::FastTransformation); } } case QVariant::Icon: { return value; } case QVariant::Pen: { const QPen pen = value.value<QPen>(); if (pen.style() != Qt::NoPen) { QPixmap p(16, 16); p.fill(QColor(0, 0, 0, 0)); QPainter painter(&p); painter.setPen(pen); painter.translate(0, 8 - pen.width() / 2); painter.drawLine(0, 0, p.width(), 0); return p; } } case QVariant::Pixmap: { const QPixmap p = value.value<QPixmap>(); if(!p.isNull()) { return QVariant::fromValue(p.scaled(16, 16, Qt::KeepAspectRatio, Qt::FastTransformation)); } } default: break; } return QVariant(); }
ToolButton* Gui::findOrCreateToolButton(const PluginGroupNodePtr & treeNode) { // Do not create an action for non user creatable plug-ins bool isUserCreatable = true; PluginPtr internalPlugin = treeNode->getPlugin(); if (internalPlugin && treeNode->getChildren().empty() && !internalPlugin->getIsUserCreatable()) { isUserCreatable = false; } if (!isUserCreatable) { return 0; } // Check for existing toolbuttons for (std::size_t i = 0; i < _imp->_toolButtons.size(); ++i) { if (_imp->_toolButtons[i]->getPluginToolButton() == treeNode) { return _imp->_toolButtons[i]; } } // Check for parent toolbutton ToolButton* parentToolButton = NULL; if ( treeNode->getParent() ) { assert(treeNode->getParent() != treeNode); if (treeNode->getParent() != treeNode) { parentToolButton = findOrCreateToolButton( treeNode->getParent() ); } } QString resourcesPath; if (internalPlugin) { resourcesPath = QString::fromUtf8(internalPlugin->getProperty<std::string>(kNatronPluginPropResourcesPath).c_str()); } QString iconFilePath = resourcesPath; StrUtils::ensureLastPathSeparator(iconFilePath); iconFilePath += treeNode->getTreeNodeIconFilePath(); QIcon toolButtonIcon, menuIcon; // Create tool icon if ( !iconFilePath.isEmpty() && QFile::exists(iconFilePath) ) { QPixmap pix(iconFilePath); int menuSize = TO_DPIX(NATRON_MEDIUM_BUTTON_ICON_SIZE); int toolButtonSize = !treeNode->getParent() ? TO_DPIX(NATRON_TOOL_BUTTON_ICON_SIZE) : TO_DPIX(NATRON_MEDIUM_BUTTON_ICON_SIZE); QPixmap menuPix = pix, toolbuttonPix = pix; if ( (std::max( menuPix.width(), menuPix.height() ) != menuSize) && !menuPix.isNull() ) { menuPix = menuPix.scaled(menuSize, menuSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); } if ( (std::max( toolbuttonPix.width(), toolbuttonPix.height() ) != toolButtonSize) && !toolbuttonPix.isNull() ) { toolbuttonPix = toolbuttonPix.scaled(toolButtonSize, toolButtonSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); } menuIcon.addPixmap(menuPix); toolButtonIcon.addPixmap(toolbuttonPix); } else { // Set default icon only if it has no parent, otherwise leave action without an icon if ( !treeNode->getParent() ) { QPixmap toolbuttonPix, menuPix; getPixmapForGrouping( &toolbuttonPix, TO_DPIX(NATRON_TOOL_BUTTON_ICON_SIZE), treeNode->getTreeNodeName() ); toolButtonIcon.addPixmap(toolbuttonPix); getPixmapForGrouping( &menuPix, TO_DPIX(NATRON_TOOL_BUTTON_ICON_SIZE), treeNode->getTreeNodeName() ); menuIcon.addPixmap(menuPix); } } // If the tool-button has no children, this is a leaf, we must create an action // At this point any plug-in MUST be in a toolbutton, so it must have a parent. assert(!treeNode->getChildren().empty() || treeNode->getParent()); int majorVersion = internalPlugin ? internalPlugin->getProperty<unsigned int>(kNatronPluginPropVersion, 0) : 1; int minorVersion = internalPlugin ? internalPlugin->getProperty<unsigned int>(kNatronPluginPropVersion, 1) : 0; ToolButton* pluginsToolButton = new ToolButton(getApp(), treeNode, treeNode->getTreeNodeID(), majorVersion, minorVersion, treeNode->getTreeNodeName(), toolButtonIcon, menuIcon); if (!treeNode->getChildren().empty()) { // For grouping items, create the menu Menu* menu = new Menu(this); menu->setTitle( pluginsToolButton->getLabel() ); menu->setIcon(menuIcon); pluginsToolButton->setMenu(menu); pluginsToolButton->setAction( menu->menuAction() ); } else { // This is a leaf (plug-in) assert(internalPlugin); assert(parentToolButton); // If this is the highest major version for this plug-in use normal label, otherwise also append the major version bool isHighestMajorVersionForPlugin = internalPlugin->getIsHighestMajorVersion(); std::string pluginLabel = !isHighestMajorVersionForPlugin ? internalPlugin->getLabelVersionMajorEncoded() : internalPlugin->getLabelWithoutSuffix(); QKeySequence defaultNodeShortcut; QString shortcutGroup = QString::fromUtf8(kShortcutGroupNodes); std::vector<std::string> groupingSplit = internalPlugin->getPropertyN<std::string>(kNatronPluginPropGrouping); for (std::size_t j = 0; j < groupingSplit.size(); ++j) { shortcutGroup.push_back( QLatin1Char('/') ); shortcutGroup.push_back(QString::fromUtf8(groupingSplit[j].c_str())); } { // If the plug-in has a shortcut get it std::list<QKeySequence> keybinds = getKeybind(shortcutGroup, QString::fromUtf8(internalPlugin->getPluginID().c_str())); if (!keybinds.empty()) { defaultNodeShortcut = keybinds.front(); } } QAction* defaultPresetAction = new QAction(this); defaultPresetAction->setShortcut(defaultNodeShortcut); defaultPresetAction->setShortcutContext(Qt::WidgetShortcut); defaultPresetAction->setText(QString::fromUtf8(pluginLabel.c_str())); defaultPresetAction->setIcon( pluginsToolButton->getMenuIcon() ); QObject::connect( defaultPresetAction, SIGNAL(triggered()), pluginsToolButton, SLOT(onTriggered()) ); const std::vector<PluginPresetDescriptor>& presets = internalPlugin->getPresetFiles(); if (presets.empty()) { // If the node has no presets, just make an action, otherwise make a menu pluginsToolButton->setAction(defaultPresetAction); } else { Menu* menu = new Menu(this); menu->setTitle( pluginsToolButton->getLabel() ); menu->setIcon(menuIcon); pluginsToolButton->setMenu(menu); pluginsToolButton->setAction( menu->menuAction() ); defaultPresetAction->setText(QString::fromUtf8(pluginLabel.c_str()) + tr(" (Default)")); menu->addAction(defaultPresetAction); for (std::vector<PluginPresetDescriptor>::const_iterator it = presets.begin(); it!=presets.end(); ++it) { QKeySequence presetShortcut; { // If the preset has a shortcut get it std::string shortcutKey = internalPlugin->getPluginID(); shortcutKey += "_preset_"; shortcutKey += it->presetLabel.toStdString(); std::list<QKeySequence> keybinds = getKeybind(shortcutGroup, QString::fromUtf8(shortcutKey.c_str())); if (!keybinds.empty()) { presetShortcut = keybinds.front(); } } QString presetLabel = QString::fromUtf8(pluginLabel.c_str()); presetLabel += QLatin1String(" ("); presetLabel += it->presetLabel; presetLabel += QLatin1String(")"); QAction* presetAction = new QAction(this); QPixmap presetPix; if (getPresetIcon(it->presetFilePath, it->presetIconFile, TO_DPIX(NATRON_MEDIUM_BUTTON_ICON_SIZE), &presetPix)) { presetAction->setIcon( presetPix ); } presetAction->setShortcut(presetShortcut); presetAction->setShortcutContext(Qt::WidgetShortcut); presetAction->setText(presetLabel); presetAction->setData(it->presetLabel); QObject::connect( presetAction, SIGNAL(triggered()), pluginsToolButton, SLOT(onTriggered()) ); menu->addAction(presetAction); } } } // if (!treeNode->getChildren().empty()) // If it has a parent, add the new tool button as a child if (parentToolButton) { parentToolButton->tryAddChild(pluginsToolButton); } _imp->_toolButtons.push_back(pluginsToolButton); return pluginsToolButton; } // findOrCreateToolButton
void UserInfoBox::updateInfo(const ServerInfo_User &user) { const UserLevelFlags userLevel(user.user_level()); QPixmap avatarPixmap; const std::string bmp = user.avatar_bmp(); if (!avatarPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) avatarPixmap = UserLevelPixmapGenerator::generatePixmap(64, userLevel, false); avatarLabel.setPixmap(avatarPixmap.scaled(avatarLabel.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); nameLabel.setText(QString::fromStdString(user.name())); realNameLabel2.setText(QString::fromStdString(user.real_name())); genderLabel2.setPixmap(GenderPixmapGenerator::generatePixmap(15, user.gender())); QString country = QString::fromStdString(user.country()); if (country.length() != 0) { countryLabel2.setPixmap(CountryPixmapGenerator::generatePixmap(15, country)); countryLabel3.setText(QString("(%1)").arg(country.toUpper())); } else { countryLabel2.setText(""); countryLabel3.setText(""); } userLevelLabel2.setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel, false)); QString userLevelText; if (userLevel.testFlag(ServerInfo_User::IsAdmin)) userLevelText = tr("Administrator"); else if (userLevel.testFlag(ServerInfo_User::IsModerator)) userLevelText = tr("Moderator"); else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) userLevelText = tr("Registered user"); else userLevelText = tr("Unregistered user"); userLevelLabel3.setText(userLevelText); QString accountAgeString = tr("Unregistered user"); if (userLevel.testFlag(ServerInfo_User::IsAdmin) || userLevel.testFlag(ServerInfo_User::IsModerator) || userLevel.testFlag(ServerInfo_User::IsRegistered)) { if (user.accountage_secs() == 0) accountAgeString = tr("Unknown"); else { qint64 seconds = user.accountage_secs(); qint64 minutes = seconds / SIXTY; qint64 hours = minutes / SIXTY; qint64 days = hours / HOURS_IN_A_DAY; qint64 years = days / DAYS_IN_A_YEAR; qint64 daysMinusYears = days - (years * DAYS_IN_A_YEAR); accountAgeString = ""; if (years >= 1) { accountAgeString = QString::number(years); accountAgeString.append(" "); accountAgeString.append(years == 1 ? tr("Year") : tr("Years")); accountAgeString.append(" "); } accountAgeString.append(QString::number(daysMinusYears)); accountAgeString.append(" "); accountAgeString.append(days == 1 ? tr("Day") : tr("Days")); } } accountAgeLabel2.setText(accountAgeString); }
void FormStyle::quickSetColor() { QFont globalFont = SystemFont; if ( ui.ccB->isChecked() && !ResetColor ) { qApp->setPalette( applicationPalette ); QPalette qSliderPalette; qSliderPalette.setBrush( QPalette::Button, sliderButtonColor ); qApp->setPalette( qSliderPalette, "QSlider" ); if ( ui.use2->isChecked() ) { QPalette tmpPalette = qApp->palette(); if ( !mainWindowPixmap.isNull() ) { QBrush brushW( mainWindowPixmap.scaled( f1.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation ) ); tmpPalette.setBrush( QPalette::Window, brushW ); } QColor colorA; colorA = tmpPalette.button().color(); colorA.setAlphaF( ui.bP2_1->value() ); tmpPalette.setBrush( QPalette::Button, colorA ); colorA = tmpPalette.base().color(); colorA.setAlphaF( ui.bP2_1->value() ); tmpPalette.setBrush( QPalette::Base, colorA ); if ( ui.bHt2->isChecked() ) { colorA = tmpPalette.highlight().color(); colorA.setAlphaF( ui.bP2_1->value() ); tmpPalette.setBrush( QPalette::Highlight, colorA ); } if ( ui.bSt2->isChecked() ) { colorA = tmpPalette.shadow().color(); colorA.setAlphaF( ui.bP2_1->value() ); tmpPalette.setBrush( QPalette::Shadow, colorA ); } f1.setPalette( tmpPalette ); } else { f1.setPalette( qApp->palette() ); } globalFont = ui.bF1->currentFont(); globalFont.setPointSize( ui.bFSize1->value() ); } else { qApp->setPalette( systemPalette ); f1.setPalette( qApp->palette() ); sliderButtonColor = qApp->palette().brush( QPalette::Button ).color(); } if ( ResetColor ) { ResetColor = false; applicationPalette = systemPalette; ui.bF1->setCurrentFont( SystemFont.toString() ); ui.bFSize1->setValue( SystemFont.pointSize() ); } QColor col = qApp->palette().window().color(); col.setAlphaF( ui.bP2_1->value() ); fsl.SetColor( col ); f1.ui.pbL->setPalette( qApp->palette() ); f1.ui.pbR->setPalette( qApp->palette() ); globalFont.setBold( false ); globalFont.setItalic( false ); globalFont.setUnderline( false ); if ( globalFont.pointSize() > 14 ) globalFont.setPointSize( 14 ); else if ( globalFont.pointSize() < 6 ) globalFont.setPointSize( 6 ); #ifndef Q_OS_MAC qApp->setFont( globalFont ); #endif }
weatherwidget::weatherwidget(QWidget *parent) : QWidget(parent) { // set initial clock time in case no web access clock = new QTime(16,18); // create default current settings currentTemp = new QLabel("86°"); currentIcon = new QLabel(); QPixmap *partlySunny = new QPixmap(":Images/weather-few-clouds.png"); *partlySunny = partlySunny->scaled(72,72,Qt::KeepAspectRatio); currentIcon->setPixmap(*partlySunny); currentCity = new QLabel("Dallas,TX"); currentTemp->setObjectName("currentTemp"); currentCity->setObjectName("currentCity"); // create default forecast day 1 values day1Label = new QLabel("Mon"); day1Icon = new QLabel(); QPixmap *partlyCloudy = new QPixmap(":Images/weather-sunny-very-few-clouds.png"); *partlyCloudy = partlyCloudy->scaled(40,40,Qt::KeepAspectRatio); day1Icon->setPixmap(*partlyCloudy); day1Low = new QLabel("83°"); day1High = new QLabel("89°"); // create default forecast day 2 values day2Label = new QLabel("Tue"); day2Icon = new QLabel(); QPixmap *overcast = new QPixmap(":Images/weather-overcast.png"); *overcast = overcast->scaled(40,40,Qt::KeepAspectRatio); day2Icon->setPixmap(*overcast); day2Low = new QLabel("81°"); day2High = new QLabel("85°"); // create default forecast day 3 values day3Label = new QLabel("Wed"); day3Icon = new QLabel(); QPixmap *tshower = new QPixmap(":Images/weather-thundershower.png"); *tshower = tshower->scaled(40,40,Qt::KeepAspectRatio); day3Icon->setPixmap(*tshower); day3Low = new QLabel("79°"); day3High = new QLabel("83°"); // create current layout QVBoxLayout *currentVLayout = new QVBoxLayout; currentVLayout->addWidget(currentTemp); currentVLayout->addWidget(currentCity); // add icon to current layout QHBoxLayout *currentHLayout = new QHBoxLayout; currentHLayout->addWidget(currentIcon); currentHLayout->addLayout(currentVLayout); // create day 1 layout QHBoxLayout *day1Layout = new QHBoxLayout; day1Layout->addWidget(day1Label); day1Layout->addWidget(day1Icon); day1Layout->addWidget(day1Low); day1Layout->addWidget(day1High); // create day 2 layout QHBoxLayout *day2Layout = new QHBoxLayout; day2Layout->addWidget(day2Label); day2Layout->addWidget(day2Icon); day2Layout->addWidget(day2Low); day2Layout->addWidget(day2High); // create day 3 layout QHBoxLayout *day3Layout = new QHBoxLayout; day3Layout->addWidget(day3Label); day3Layout->addWidget(day3Icon); day3Layout->addWidget(day3Low); day3Layout->addWidget(day3High); // create final layout QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(currentHLayout); mainLayout->addLayout(day1Layout); mainLayout->addLayout(day2Layout); mainLayout->addLayout(day3Layout); // show layout setLayout(mainLayout); }
void ZoomWidget::doPainting(QPainter& painter) { //paint the screenshot if(!m_pixmap.isNull()) { QPixmap scaled = m_pixmap.copy(QRect(QPoint(0, 0), size() / m_zoomFactor)); scaled = scaled.scaled(scaled.size()*m_zoomFactor); painter.drawPixmap(rulerWidth, rulerWidth, scaled); } //mark active pixels QPen pen; pen.setStyle(Qt::SolidLine); pen.setColor(QColor(255, 0, 0, 100)); painter.setPen(pen); QBrush brush(QColor(255, 0, 0, 100)); if(m_markColor.isValid()) { QImage image = m_pixmap.toImage(); for(int x=0;x<m_pixmap.size().width();x++) { for(int y=0;y<m_pixmap.size().height();y++) { if(image.pixel(x, y)==m_markColor.rgb()) { //painter.drawRect(rulerWidth+x*m_zoomFactor, rulerWidth+y*m_zoomFactor, m_zoomFactor, m_zoomFactor); painter.fillRect(QRect(rulerWidth+x*m_zoomFactor, rulerWidth+y*m_zoomFactor, m_zoomFactor, m_zoomFactor), brush); } } } } //draw grid if(m_gridColor.isValid()) { pen.setStyle(Qt::SolidLine); QColor gridPenColor(m_gridColor); gridPenColor.setAlpha(200); pen.setColor(gridPenColor); painter.setPen(pen); static const int gridSize=10; for(int x=rulerWidth;x<width();x+=gridSize*m_zoomFactor) { painter.drawLine(x, rulerWidth, x, height()-rulerWidth); } for(int y=rulerWidth;y<height();y+=gridSize*m_zoomFactor) { painter.drawLine(rulerWidth, y, width()-rulerWidth, y); } } pen.setStyle(Qt::SolidLine); pen.setColor(QColor(0, 0, 0)); painter.setPen(pen); //draw the rulers: painter.fillRect (0, 0, width(), rulerWidth, QBrush(QColor(255, 255, 255))); painter.fillRect (0, 0, rulerWidth, height(), QBrush(QColor(255, 255, 255))); //draw the ruler ticks QFont font; font.setPointSize(6); painter.setFont(font); for(int i=0;i<(width()-rulerWidth)/(20);i++) { int x = i*20 + rulerWidth; if(i%2==0) { painter.drawLine(x, rulerWidth-8, x, rulerWidth); painter.drawText(QRect(x-9, 2, 18, 10), Qt::AlignCenter, QString("%1").arg(i*20/m_zoomFactor)); } else { painter.drawLine(x, rulerWidth-5, x, rulerWidth); } } for(int i=0;i<(height()-rulerWidth)/(20);i++) { int y = i*20 + rulerWidth; if(i%2==0) { painter.drawLine(rulerWidth-8, y, rulerWidth, y); painter.drawText(QRect(2, y-9, 10, 18), Qt::AlignCenter, QString("%1").arg(i*20/m_zoomFactor)); } else { painter.drawLine(rulerWidth-5, y, rulerWidth, y); } } //draw the lines QList<int> posX; QList<int> posY; for(int i=0;i<lines.count();i++) { if(hasCurrentLine && i==currentLine) { QPen pen; pen.setStyle(Qt::DashLine); pen.setColor(QColor(255, 0, 0)); painter.setPen(pen); } else { QPen pen; pen.setStyle(Qt::SolidLine); pen.setColor(QColor(0, 0, 255)); painter.setPen(pen); } Line* line = lines.at(i); if(line->orientation == Qt::Horizontal) { painter.drawLine(line->position*m_zoomFactor + rulerWidth, rulerWidth, line->position*m_zoomFactor + rulerWidth, height()); posX << line->position; } else if (line->orientation == Qt::Vertical) { painter.drawLine(rulerWidth, line->position*m_zoomFactor + rulerWidth, width(), line->position*m_zoomFactor + rulerWidth); posY << line->position; } } //on the edgre make 30px lighter painter.fillRect(rulerWidth, height()-30, width(), 30, QBrush(QColor(255, 255, 255, 200))); painter.fillRect(width()-30, rulerWidth, 30, height()-rulerWidth-30, QBrush(QColor(255, 255, 255, 200))); //array for the pointer <---> static const QPoint arrowPoints[3] = { QPoint(0, 0), QPoint(8, 4), QPoint(0, 8) }; //measure the number of px between the lines (x) qSort(posX); font.setPointSize(8); painter.setFont(font); painter.setPen(QColor(0, 0, 0)); int last = 0; foreach(int x, posX) { painter.drawLine(last*m_zoomFactor + rulerWidth, height()-10, x*m_zoomFactor + rulerWidth, height()-10); painter.drawText(QRect(last*m_zoomFactor + rulerWidth, height()-30, (x-last)*m_zoomFactor, 20), Qt::AlignCenter | Qt::AlignBottom, QString("%1").arg(x-last)); bool arrowOnOutside = false; if((x-last)*m_zoomFactor < 40) { qSwap(x, last); arrowOnOutside = true; } painter.save(); //arrow right painter.setBrush(QBrush(QColor(0, 0, 0))); painter.translate(x*m_zoomFactor + rulerWidth-8, height()-10 -4); painter.drawPolygon(arrowPoints, 3, Qt::WindingFill); //arrow left painter.translate((last-x)*m_zoomFactor+16, 8); painter.rotate(180); painter.drawPolygon(arrowPoints, 3); painter.restore(); if(!arrowOnOutside) //else qSwaped allready last = x; }
void ScreenshotSpreader::Handle(const Client& client, mc::IProtocolRef protocol, IServerControlRef /* server */) { if ( !client.IsScreenCaptureEnabled() ) return; // Acquire mouse cursor position. RemotePC::ScreenPoint position = RemotePC::HardwareProvider::Instance().GetMouseControl()->GetPosition(); // Calculate bounding box around current mouse position. float blockSize = 256.0f; float zoomLevel = client.GetZoomLevel(); int imageSize = (int)( blockSize * zoomLevel ); int leftX = position.x_ - imageSize / 2; int topY = position.y_ - imageSize / 2; int rightX = leftX + imageSize; int bottomY = topY + imageSize; // Find screen to which cursor currently belongs. QDesktopWidget* desktop = QApplication::desktop(); int screenNumber = desktop->screenNumber(QPoint(position.x_, position.y_)); QWidget* screen = desktop->screen(screenNumber); QRect geometry = screen->geometry(); // Cut areas beyond the surface of the screen. int leftdX = ( leftX < geometry.left() ) ? ( geometry.left() - leftX ) : 0; int topdY = ( topY < geometry.top() ) ? ( geometry.top() - topY ) : 0; int rightdX = ( rightX > geometry.right() ) ? ( rightX - geometry.right() ) : 0; int bottomdY = ( bottomY >= geometry.bottom() ) ? ( bottomY - geometry.bottom() ) : 0; leftX += leftdX; topY += topdY; rightX += rightdX; bottomY += bottomdY; int fragmentWidth = imageSize - leftdX - rightdX; int fragmentHeight = imageSize - topdY - bottomdY; bool isBoundary = ( leftdX > 0 ) || ( topdY > 0 ) || ( rightdX > 0 ) || ( bottomdY > 0 ); // Grab part of the screen. QPixmap fragment = QApplication::primaryScreen()->grabWindow( QApplication::desktop()->winId(), leftX, topY, fragmentWidth, fragmentHeight); // Check to see if anything was actually grabbed. fragmentWidth = fragment.width(); fragmentHeight = fragment.height(); if ( fragmentWidth <= 0 || fragmentHeight <= 0 ) { return; } if ( isBoundary ) { // Image was grabbed right next to one of screen edges. // Scale image first. QPainter's scaling does not always work even with QPainter::SmoothPixmapTransform. fragment = fragment.scaled( QSize(fragmentWidth * blockSize / imageSize, fragmentHeight * blockSize / imageSize), Qt::KeepAspectRatio, Qt::SmoothTransformation); // Locate grabbed fragment appropriately in the resulting image. QPixmap temp(blockSize, blockSize); QPainter painter(&temp); painter.fillRect(0, 0, blockSize, blockSize, QColor(Qt::black)); painter.drawPixmap(QPoint(leftdX * blockSize / imageSize, topdY * blockSize / imageSize), fragment); fragment = temp; } else { if ( imageSize != (int)blockSize ) { // Image was grabbed from within the screen. fragment = fragment.scaled( QSize(blockSize, blockSize), Qt::KeepAspectRatio, Qt::SmoothTransformation); } } // Construct screenshot message from QT image. QByteArray imageBytes; QBuffer imageBuffer(&imageBytes); imageBuffer.open(QIODevice::WriteOnly); #if !defined(IREMOTE_NO_QT_PLUGINS) fragment.save(&imageBuffer, "JPG", Config::Instance().GetSFBCompression()); #else fragment.save(&imageBuffer, "PNG", Config::Instance().GetSFBCompression()); #endif // Construct message object. mc::IMessagePtr message( mc::Class< RemotePC::ScreenshotMessage >::Create( imageBytes.size(), imageBytes.constData() ) ); // Send image to the client. protocol->Send( message ); }
void cThumbnailWidget::AssignParameters( const cParameterContainer &_params, const cFractalContainer &_fractal) { if (image) { if (!params) params = new cParameterContainer; if (!fractal) fractal = new cFractalContainer; *params = _params; *fractal = _fractal; params->Set("image_width", tWidth * oversample); params->Set("image_height", tHeight * oversample); params->Set("stereo_mode", int(cStereo::stereoRedCyan)); params->Set("DOF_max_noise", params->Get<double>("DOF_max_noise") * 10.0); params->Set("DOF_min_samples", 5); double distance = cInterface::GetDistanceForPoint(params->Get<CVector3>("camera"), params, fractal); if (distance < 1e-5) { params->Set("opencl_mode", 0); } cSettings tempSettings(cSettings::formatCondensedText); tempSettings.CreateText(params, fractal); oldHash = hash; hash = tempSettings.GetHashCode(); if (hash != oldHash) { stopRequest = true; while (image->IsUsed()) { // just wait and pray } emit settingsChanged(); isRendered = false; hasParameters = true; QString thumbnailFileName = GetThumbnailFileName(); if (QFileInfo::exists(thumbnailFileName) && !disableThumbnailCache) { stopRequest = true; isRendered = true; while (image->IsUsed()) { // just wait and pray } QPixmap pixmap; pixmap.load(thumbnailFileName); pixmap = pixmap.scaled(tWidth, tHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); QImage qImage = pixmap.toImage(); qImage = qImage.convertToFormat(QImage::Format_RGB888); sRGB8 *previewPointer = reinterpret_cast<sRGB8 *>(image->GetPreviewPrimaryPtr()); sRGB8 *preview2Pointer = reinterpret_cast<sRGB8 *>(image->GetPreviewPtr()); int bWidth = qImage.width(); int bHeight = qImage.height(); if (!qImage.isNull()) { for (int y = 0; y < bHeight; y++) { sRGB8 *line = reinterpret_cast<sRGB8 *>(qImage.scanLine(y)); for (int x = 0; x < bWidth; x++) { sRGB8 pixel(static_cast<unsigned short>(line[x].R), static_cast<unsigned short>(line[x].G), static_cast<unsigned short>(line[x].B)); previewPointer[x + y * bWidth] = pixel; preview2Pointer[x + y * bWidth] = pixel; } } } delete params; params = nullptr; delete fractal; fractal = nullptr; emit thumbnailRendered(); } else { if (!disableTimer) { // render thumbnail after random time. It forces rendering of widgets when they are not // visible. It makes rendering of widgets when they are idle. timer->start(Random(1000000) * 10 + 60000); } } } } else { qCritical() << "Image not yet allocated!"; } }
void GcWindow::paintEvent(QPaintEvent * /*event*/) { static QPixmap closeImage = QPixmap(":images/toolbar/popbutton.png"); static QPixmap aluBar = QPixmap(":images/aluBar.png"); static QPixmap aluBarDark = QPixmap(":images/aluBarDark.png"); static QPixmap aluLight = QPixmap(":images/aluLight.jpg"); static QPixmap carbon = QPixmap(":images/carbon.jpg"); static QPalette defaultPalette; // setup a painter and the area to paint QPainter painter(this); // background light gray for now? QRect all(0,0,width(),height()); painter.fillRect(all, property("color").value<QColor>()); if (contentsMargins().top() > 0) { // fill in the title bar QRect bar(0,0,width(),contentsMargins().top()); if (contentsMargins().top() < 25) { QColor bg; if (property("active").toBool() == true) { bg = GColor(CTILEBARSELECT); painter.drawPixmap(bar, aluBar); } else { bg = GColor(CTILEBAR); painter.drawPixmap(bar, aluBarDark); } } else { painter.setPen(Qt::darkGray); painter.drawRect(QRect(0,0,width()-1,height()-1)); } // heading QFont font; font.setPointSize((contentsMargins().top()/2)+2); font.setWeight(QFont::Bold); painter.setFont(font); QString subtitle = property("subtitle").toString(); QString title = property("title").toString(); QString heading = subtitle != "" ? subtitle : title; // embossed... QRect shad = bar; shad.setY(bar.y()+2); //shad.setX(bar.x()+2); painter.setPen(QColor(255,255,255,180)); painter.drawText(shad, heading, Qt::AlignVCenter | Qt::AlignCenter); painter.setPen(QColor(0,0,0,200)); painter.drawText(bar, heading, Qt::AlignVCenter | Qt::AlignCenter); // border painter.setBrush(Qt::NoBrush); if (underMouse()) { QPixmap sized = closeImage.scaled(QSize(contentsMargins().top()-6, contentsMargins().top()-6)); //painter.drawPixmap(width()-3-sized.width(), 3, sized.width(), sized.height(), sized); } else { painter.setPen(Qt::darkGray); //painter.drawRect(QRect(0,0,width()-1,height()-1)); //XXX pointless } } else { // is this a layout manager? // background light gray for now? QRect all(0,0,width(),height()); if (property("isManager").toBool() == true) { //painter.drawTiledPixmap(all, carbon); painter.fillRect(all, QColor("#B3B4BA")); } else { //painter.drawTiledPixmap(all, aluLight); } } }
void PreviewWidget::paintEvent( QPaintEvent * ) { int i_total = 0, i_offset = 0, i; QPainter painter( this ); QPixmap pixmaps[3]; for( int i=0; i<3; i++ ) { #if HAS_QT5 pixmaps[i] = bars[i]->grab( bars[i]->contentsRect() ); #else pixmaps[i] = QPixmap::grabWidget( bars[i], bars[i]->contentsRect() ); #endif for( int j=0; j < bars[i]->layout()->count(); j++ ) { QLayoutItem *item = bars[i]->layout()->itemAt( j ); if ( !strcmp( item->widget()->metaObject()->className(), "QLabel" ) ) { QPainter eraser( &pixmaps[i] ); eraser.fillRect( item->geometry(), palette().background() ); eraser.end(); } } pixmaps[i] = pixmaps[i].scaled( size(), Qt::KeepAspectRatio ); } for( i=0; i<3; i++ ) i_total += pixmaps[i].size().height(); /* Draw top bars */ i = ( b_top ) ? 1 : 3; for( ; i<3; i++ ) { painter.drawPixmap( pixmaps[i].rect().translated( 0, i_offset ), pixmaps[i] ); i_offset += pixmaps[i].rect().height(); } /* Draw central area */ QRect conearea( 0, i_offset, size().width(), size().height() - i_total ); painter.fillRect( conearea, Qt::black ); QPixmap cone = QPixmap( ":/logo/vlc128.png" ); if ( ( conearea.size() - QSize(10, 10) - cone.size() ).isEmpty() ) cone = cone.scaled( conearea.size() - QSize(10, 10), Qt::KeepAspectRatio ); if ( cone.size().isValid() ) { painter.drawPixmap( ((conearea.size() - cone.size()) / 2).width(), i_offset + ((conearea.size() - cone.size()) / 2).height(), cone ); } /* Draw bottom bars */ i_offset += conearea.height(); for( i = 0 ; i< ((b_top) ? 1 : 3); i++ ) { painter.drawPixmap( pixmaps[i].rect().translated( 0, i_offset ), pixmaps[i] ); i_offset += pixmaps[i].rect().height(); } /* Draw overlay */ painter.fillRect( rect(), QColor( 255, 255, 255, 128 ) ); painter.end(); }
void MainWindow::gameInit() { // background music bgm->play(); // Setting the QGraphicsScene scene = new QGraphicsScene(0,0,width(),ui->graphicsView->height()); scene->setBackgroundBrush(QPixmap(":/image/background.png")); ui->graphicsView->setScene(scene); // Create world world = new b2World(b2Vec2(0.0f, -9.8f)); // Setting Size GameItem::setGlobalSize(QSizeF(40,18),size()); // Create ground itemList.push_back(new Land(20,1.5,40,3,QPixmap(":/image/ground.png").scaled(width(),height()/6.0),world,scene)); // Create slingshot shoot = new Shoot(); QPixmap sh; sh.load(":/image/shot.png"); sh = sh.scaled( sh.width()*3/4, sh.height()*3/4 ,Qt::KeepAspectRatio ); shoot->setPixmap(sh); shoot->setPos(150,300); scene->addItem(shoot); // Create Line line1 = scene->addLine(-10,-10,-10,-10,QPen(Qt::darkRed,4)); line2 = scene->addLine(-10,-10,-10,-10,QPen(Qt::darkRed,4)); // Create bird setbird[5] = new Setbird(); QPixmap b5; b5.load(":/image/RedBird.png"); setbird[5]->setPixmap(b5); setbird[5]->setPos(150,300); scene->addItem(setbird[5]); setbird[4] = new Setbird(); QPixmap b4; b4.load(":/image/YellowBird.png"); setbird[4]->setPixmap(b4); setbird[4]->setPos(90,396); scene->addItem(setbird[4]); setbird[3] = new Setbird(); QPixmap b3; b3.load(":/image/BlueBird.png"); setbird[3]->setPixmap(b3); setbird[3]->setPos(30,394); scene->addItem(setbird[3]); // Create barriers wood[0] = new Wood(24.0f,4.0f,0.4f,1.0f,&timer,QPixmap(":/image/woodbarv.png").scaled(25,90),world,scene); itemList.push_back(wood[0]); wood[1] = new Wood(28.5f,4.0f,0.4f,1.0f,&timer,QPixmap(":/image/woodbarv.png").scaled(25,90),world,scene); itemList.push_back(wood[1]); wood[2] = new Wood(25.6f,7.0f,3.0f,0.4f,&timer,QPixmap(":/image/woodbarh.png").scaled(150,25),world,scene); itemList.push_back(wood[2]); wood[3] = new Wood(30.0f,4.0f,2.0f,0.5f,&timer,QPixmap(":/image/box.png").scaled(96,60),world,scene); itemList.push_back(wood[3]); rock[0] = new Rock(26.0f,8.5f,0.7f,0.8f,&timer,QPixmap(":/image/rocksq.png").scaled(42,42),world,scene); itemList.push_back(rock[0]); rock[1] = new Rock(27.0f,8.5f,0.7f,0.8f,&timer,QPixmap(":/image/rocksq.png").scaled(42,42),world,scene); itemList.push_back(rock[1]); wood[4] = new Wood(27.0f,9.8f,0.8f,0.8f,&timer,QPixmap(":/image/boxsq.png").scaled(47,47),world,scene); itemList.push_back(wood[4]); wood[5] = new Wood(35.5f,4.2f,1.0f,1.2f,&timer,QPixmap(":/image/boxf.png").scaled(87,100),world,scene); itemList.push_back(wood[5]); rock[2] = new Rock(35.7f,8.0f,0.9f,&timer,QPixmap(":/image/rock.png"),world,scene); itemList.push_back(rock[2]); // Create pig pig[0] = new Pig(25.2f,3.4f,0.4f,&timer,QPixmap(":/image/pig1.png"),world,scene); itemList.push_back(pig[0]); pig[1] = new Pig(27.2f,10.5f,0.6f,&timer,QPixmap(":/image/pig2.png"),world,scene); itemList.push_back(pig[1]); pig[2] = new Pig(30.7f,4.5f,0.6f,&timer,QPixmap(":/image/pig2.png"),world,scene); itemList.push_back(pig[2]); }
void MonthWidget::setThumb(const QPixmap &pic) { thumb_ = pic.scaled(thumbSize, Qt::KeepAspectRatio); update(); }
void QWindowsOleDropSource::createCursors() { const QDrag *drag = m_drag->currentDrag(); const QPixmap pixmap = drag->pixmap(); const bool hasPixmap = !pixmap.isNull(); // Find screen for drag. Could be obtained from QDrag::source(), but that might be a QWidget. const QPlatformScreen *platformScreen = QWindowsContext::instance()->screenManager().screenAtDp(QWindowsCursor::mousePosition()); if (!platformScreen) { if (const QScreen *primaryScreen = QGuiApplication::primaryScreen()) platformScreen = primaryScreen->handle(); } Q_ASSERT(platformScreen); QPlatformCursor *platformCursor = platformScreen->cursor(); qreal pixmapScaleFactor = 1; qreal hotSpotScaleFactor = 1; if (m_mode != TouchDrag) { // Touch drag: pixmap is shown in a separate QWindow, which will be scaled.) hotSpotScaleFactor = QHighDpiScaling::factor(platformScreen); pixmapScaleFactor = hotSpotScaleFactor / pixmap.devicePixelRatio(); } QPixmap scaledPixmap = qFuzzyCompare(pixmapScaleFactor, 1.0) ? pixmap : pixmap.scaled((QSizeF(pixmap.size()) * pixmapScaleFactor).toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation); scaledPixmap.setDevicePixelRatio(1); Qt::DropAction actions[] = { Qt::MoveAction, Qt::CopyAction, Qt::LinkAction, Qt::IgnoreAction }; int actionCount = int(sizeof(actions) / sizeof(actions[0])); if (!hasPixmap) --actionCount; // No Qt::IgnoreAction unless pixmap const QPoint hotSpot = qFuzzyCompare(hotSpotScaleFactor, 1.0) ? drag->hotSpot() : (QPointF(drag->hotSpot()) * hotSpotScaleFactor).toPoint(); for (int cnum = 0; cnum < actionCount; ++cnum) { const Qt::DropAction action = actions[cnum]; QPixmap cursorPixmap = drag->dragCursor(action); if (cursorPixmap.isNull() && platformCursor) cursorPixmap = static_cast<QWindowsCursor *>(platformCursor)->dragDefaultCursor(action); const qint64 cacheKey = cursorPixmap.cacheKey(); const auto it = m_cursors.find(action); if (it != m_cursors.end() && it.value().cacheKey == cacheKey) continue; if (cursorPixmap.isNull()) { qWarning("%s: Unable to obtain drag cursor for %d.", __FUNCTION__, action); continue; } QPoint newHotSpot(0, 0); QPixmap newPixmap = cursorPixmap; if (hasPixmap) { const int x1 = qMin(-hotSpot.x(), 0); const int x2 = qMax(scaledPixmap.width() - hotSpot.x(), cursorPixmap.width()); const int y1 = qMin(-hotSpot.y(), 0); const int y2 = qMax(scaledPixmap.height() - hotSpot.y(), cursorPixmap.height()); QPixmap newCursor(x2 - x1 + 1, y2 - y1 + 1); newCursor.fill(Qt::transparent); QPainter p(&newCursor); const QPoint pmDest = QPoint(qMax(0, -hotSpot.x()), qMax(0, -hotSpot.y())); p.drawPixmap(pmDest, scaledPixmap); p.drawPixmap(qMax(0, hotSpot.x()),qMax(0, hotSpot.y()), cursorPixmap); newPixmap = newCursor; newHotSpot = QPoint(qMax(0, hotSpot.x()), qMax(0, hotSpot.y())); } if (const HCURSOR sysCursor = QWindowsCursor::createPixmapCursor(newPixmap, newHotSpot)) { const CursorEntry entry(newPixmap, cacheKey, CursorHandlePtr(new CursorHandle(sysCursor)), newHotSpot); if (it == m_cursors.end()) m_cursors.insert(action, entry); else it.value() = entry; } } #ifndef QT_NO_DEBUG_OUTPUT if (lcQpaMime().isDebugEnabled()) qCDebug(lcQpaMime) << __FUNCTION__ << "pixmap" << pixmap.size() << m_cursors.size() << "cursors:\n" << m_cursors; #endif // !QT_NO_DEBUG_OUTPUT }
void BCBoard::setCursor(int type) { QPixmap pixmap = BattleCity::cursorPixmap(BattleCity::ObstacleType(type)); pixmap = pixmap.scaled(QSize(pixmap.width() * 2, pixmap.height() * 2)); QDeclarativeItem::setCursor(QCursor(pixmap)); }
QPixmap ImageRegistry::pixmap( const QString& image, const QSize& size, TomahawkUtils::ImageMode mode, float opacity, QColor tint ) { if ( size.width() < 0 || size.height() < 0 ) { Q_ASSERT( false ); return QPixmap(); } QHash< qint64, QPixmap > subsubcache; QHash< int, QHash< qint64, QPixmap > > subcache; if ( s_cache.contains( image ) ) { subcache = s_cache.value( image ); if ( subcache.contains( mode ) ) { subsubcache = subcache.value( mode ); const qint64 ck = cacheKey( size, opacity, tint ); if ( subsubcache.contains( ck ) ) { return subsubcache.value( ck ); } } } // Image not found in cache. Let's load it. QPixmap pixmap; if ( image.toLower().endsWith( ".svg" ) ) { QSvgRenderer svgRenderer( image ); QPixmap p( size.isNull() || size.height() == 0 || size.width() == 0 ? svgRenderer.defaultSize() : size ); p.fill( Qt::transparent ); QPainter pixPainter( &p ); pixPainter.setOpacity( opacity ); svgRenderer.render( &pixPainter ); pixPainter.end(); if ( tint.alpha() > 0 ) p = TomahawkUtils::tinted( p, tint ); pixmap = p; } else pixmap = QPixmap( image ); if ( !pixmap.isNull() ) { switch ( mode ) { case TomahawkUtils::RoundedCorners: pixmap = TomahawkUtils::createRoundedImage( pixmap, size ); break; default: break; } if ( !size.isNull() && pixmap.size() != size ) { if ( size.width() == 0 ) { pixmap = pixmap.scaledToHeight( size.height(), Qt::SmoothTransformation ); } else if ( size.height() == 0 ) { pixmap = pixmap.scaledToWidth( size.width(), Qt::SmoothTransformation ); } else pixmap = pixmap.scaled( size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ); } putInCache( image, size, mode, opacity, pixmap, tint ); } return pixmap; }
void MainWindow::showEvent(QShowEvent *) { //Setting the QGraphicsScene scene = new QGraphicsScene(0,0,width(),ui->graphicsView->height()); ui->graphicsView->setScene(scene); //set background QImage bg; bg.load(":/image/background.jpg"); bg = bg.scaled(960,540); scene->setBackgroundBrush(bg); //bgm bgm = new QMediaPlayer(); bgm->setMedia(QUrl("qrc:/sound/Super Mario Bros. Music - Ground Theme (1).1.mp3")); bgm->setVolume(50); bgm->play(); //Create world world = new b2World(b2Vec2(0.0f, -9.8f)); //Setting Size GameItem::setGlobalSize(QSizeF(32,18),size()); //Create ground itemList.push_back(new Land(16,1.5,32,3,QPixmap(":/image/ground.png").scaled(width()*2,height()/5.0),world,scene)); //add slingshot image (just image, no box2D body) QGraphicsPixmapItem *slingShot = new QGraphicsPixmapItem(); QPixmap slingPic; slingPic.load(":/image/slingshot.png"); slingPic = slingPic.scaled(slingPic.width()*0.07, slingPic.height()*0.07, Qt::KeepAspectRatio); slingShot->setPixmap(slingPic); slingShot->setPos(170,300); scene->addItem(slingShot); //Create slingshot(removed tempararily) //sling = new Slingshot(3.5,5.5,2.5,4,QPixmap(":/image/slingshot.png").scaled(width()*0.06,height()*0.3),world,scene); /*Replace slingshot with a base point(with respect to the final cursor point we dragged to) * and try to use ApplyForce() on the boody (requires b2Vec2(force)) */ //add base point(reference point), to indicate direction QPen pen; scene->addEllipse(200,300,10,10,pen,QBrush(Qt::red)); //Create bird mushroom = new Bird(6,8,0.5f,&timer,QPixmap(":/image/mushroom.png").scaled(height()/8.0,height()/8.0),world,scene); goomba = new FloppyBird(7,8,0.5f,&timer,QPixmap(":/image/goo.png").scaled(height()/8.0,height()/8.0),world,scene); kirby = new SprintBird(8,8,0.5f,&timer,QPixmap(":/image/kirby.png").scaled(height()/7.0,height()/7.0),world,scene); turtle = new StrikeBird(9,8,0.5f,&timer,QPixmap(":/image/turtle.png").scaled(height()/8.0,height()/8.0),world,scene); fist = new Bird(18,40,0.9f,&timer,QPixmap(":/image/fist.png").scaled(height()*0.5,height()*0.5),world,scene); fist->g_body->SetAwake(false); //deactivate the fist at first, wait for strike bird //Create barrier wood = new Barrier(24,6,1,5,&timer,QPixmap(":/image/barrier.png").scaled(height()/10.0,height()/2.0),world,scene); wood2 = new Barrier(18,6,1,5,&timer,QPixmap(":/image/barrier.png").scaled(height()/10.0,height()/2.0),world,scene); hori_wood = new Barrier(19,16,5,1,&timer,QPixmap(":/image/barrier_hori.png").scaled(height()/2.0,height()/2.8),world,scene); //Create enemy lbj = new Bird(21,6,1.0f,&timer,QPixmap(":/image/LBJ.png").scaled(height()/6.0,height()/5.0),world,scene); //Store birds BirdList.push_back(mushroom); BirdList.push_back(goomba); BirdList.push_back(kirby); BirdList.push_back(turtle); //Store barriers and enemy itemList.push_back(wood); itemList.push_back(wood2); itemList.push_back(hori_wood); itemList.push_back(lbj); itemList.push_back(fist); //Reset button QPushButton *resetBtn = new QPushButton("RESET"); resetBtn->setFont(QFont("Courier",16,QFont::Bold)); resetBtn->setGeometry(100,0,70,40); scene->addWidget(resetBtn); //Quit button QPushButton *quitBtn = new QPushButton("QUIT"); quitBtn->setFont(QFont("Courier",16,QFont::Bold)); quitBtn->setGeometry(0,0,70,40); scene->addWidget(quitBtn); //scoreboard QLabel *scoreboard = new QLabel("SCORE:"); scoreboard->setFont(QFont("Courier",20,QFont::Bold)); scoreboard->setGeometry(200,0,100,40); scene->addWidget(scoreboard); //score score = new QLabel(QString::number(scoreNum)); score->setFont(QFont("Courier",20,QFont::Bold)); score->setGeometry(330,0,200,40); scene->addWidget(score); //if(!isConnected) //{ // Timer and calculate score connect(&timer,SIGNAL(timeout()),this,SLOT(tick())); //} timer.start(100/6); //button connect connect(this,SIGNAL(quitGame()),this,SLOT(QUITSLOT())); connect(quitBtn,SIGNAL(clicked()),this,SLOT(closeGame())); connect(resetBtn,SIGNAL(clicked()),this,SLOT(resetGame())); }
void CLabel::setPixmap(const QPixmap &pixmap) { m_pLabelIcon->setPixmap(pixmap.scaled(QSize(30, 30), Qt::KeepAspectRatio, Qt::SmoothTransformation)); }
KnobGuiPtr DockablePanelPrivate::findKnobGuiOrCreate(const KnobPtr & knob, bool makeNewLine, QWidget* lastRowWidget, const std::vector< boost::shared_ptr< KnobI > > & knobsOnSameLine) { assert(knob); boost::shared_ptr<KnobGroup> isGroup = boost::dynamic_pointer_cast<KnobGroup>(knob); boost::shared_ptr<KnobPage> isPage = boost::dynamic_pointer_cast<KnobPage>(knob); for (KnobsGuiMapping::const_iterator it = _knobs.begin(); it != _knobs.end(); ++it) { if ( (it->first.lock() == knob) && it->second ) { if (isPage) { return it->second; } else if ( isGroup && ( ( !isGroup->isTab() && it->second->hasWidgetBeenCreated() ) || isGroup->isTab() ) ) { return it->second; } else if ( it->second->hasWidgetBeenCreated() ) { return it->second; } else { break; } } } if (isPage) { if ( isPage->getChildren().empty() ) { return KnobGuiPtr(); } getOrCreatePage(isPage); KnobsVec children = isPage->getChildren(); initializeKnobVector(children, lastRowWidget); return KnobGuiPtr(); } KnobGuiPtr ret = createKnobGui(knob); if (!ret) { return KnobGuiPtr(); } KnobPtr parentKnob = knob->getParentKnob(); boost::shared_ptr<KnobGroup> parentIsGroup = boost::dynamic_pointer_cast<KnobGroup>(parentKnob); KnobGuiGroup* parentGui = 0; /// if this knob is within a group, make sure the group is created so far if (parentIsGroup) { parentGui = dynamic_cast<KnobGuiGroup*>( findKnobGuiOrCreate( parentKnob, true, ret->getFieldContainer() ).get() ); } ///So far the knob could have no parent, in which case we force it to be in the default page. if (!parentKnob) { boost::shared_ptr<KnobPage> defPage = ensureDefaultPageKnobCreated(); defPage->addKnob(knob); parentKnob = defPage; } ///if widgets for the KnobGui have already been created, don't do the following ///For group only create the gui if it is not a tab. if ( isGroup && isGroup->isTab() ) { boost::shared_ptr<KnobPage> parentIsPage = boost::dynamic_pointer_cast<KnobPage>(parentKnob); if (!parentKnob || parentIsPage) { PageMap::iterator page = _pages.end(); if (!parentKnob) { page = getDefaultPage(knob); } else { page = getOrCreatePage(parentIsPage); } bool existed = true; if (!page->second.groupAsTab) { existed = false; page->second.groupAsTab = new TabGroup(_publicInterface); } page->second.groupAsTab->addTab( isGroup, QString::fromUtf8( isGroup->getLabel().c_str() ) ); ///retrieve the form layout QGridLayout* layout; if (_useScrollAreasForTabs) { layout = dynamic_cast<QGridLayout*>( dynamic_cast<QScrollArea*>(page->second.tab)->widget()->layout() ); } else { layout = dynamic_cast<QGridLayout*>( page->second.tab->layout() ); } assert(layout); if (!existed) { layout->addWidget(page->second.groupAsTab, page->second.currentRow, 0, 1, 2); } page->second.groupAsTab->refreshTabSecretNess( isGroup.get() ); } else { assert(parentIsGroup); assert(parentGui); TabGroup* groupAsTab = parentGui->getOrCreateTabWidget(); groupAsTab->addTab( isGroup, QString::fromUtf8( isGroup->getLabel().c_str() ) ); if ( parentIsGroup && parentIsGroup->isTab() ) { ///insert the tab in the layout of the parent ///Find the page in the parentParent group KnobPtr parentParent = parentKnob->getParentKnob(); assert(parentParent); boost::shared_ptr<KnobGroup> parentParentIsGroup = boost::dynamic_pointer_cast<KnobGroup>(parentParent); boost::shared_ptr<KnobPage> parentParentIsPage = boost::dynamic_pointer_cast<KnobPage>(parentParent); assert(parentParentIsGroup || parentParentIsPage); TabGroup* parentTabGroup = 0; if (parentParentIsPage) { PageMap::iterator page = getOrCreatePage(parentParentIsPage); assert( page != _pages.end() ); parentTabGroup = page->second.groupAsTab; } else { KnobsGuiMapping::iterator it = findKnobGui(parentParent); assert( it != _knobs.end() ); KnobGuiGroup* parentParentGroupGui = dynamic_cast<KnobGuiGroup*>( it->second.get() ); assert(parentParentGroupGui); parentTabGroup = parentParentGroupGui->getOrCreateTabWidget(); } QGridLayout* layout = parentTabGroup->addTab( parentIsGroup, QString::fromUtf8( parentIsGroup->getLabel().c_str() ) ); assert(layout); layout->addWidget(groupAsTab, 0, 0, 1, 2); } else { boost::shared_ptr<KnobPage> topLevelPage = knob->getTopLevelPage(); PageMap::iterator page = getOrCreatePage(topLevelPage); assert( page != _pages.end() ); ///retrieve the form layout QGridLayout* layout; if (_useScrollAreasForTabs) { layout = dynamic_cast<QGridLayout*>( dynamic_cast<QScrollArea*>(page->second.tab)->widget()->layout() ); } else { layout = dynamic_cast<QGridLayout*>( page->second.tab->layout() ); } assert(layout); layout->addWidget(groupAsTab, page->second.currentRow, 0, 1, 2); } groupAsTab->refreshTabSecretNess( isGroup.get() ); } } else if ( !ret->hasWidgetBeenCreated() ) { KnobPtr parentKnobTmp = parentKnob; while (parentKnobTmp) { KnobPtr parent = parentKnobTmp->getParentKnob(); if (!parent) { break; } else { parentKnobTmp = parent; } } ////find in which page the knob should be boost::shared_ptr<KnobPage> isTopLevelParentAPage = boost::dynamic_pointer_cast<KnobPage>(parentKnobTmp); assert(isTopLevelParentAPage); PageMap::iterator page = getOrCreatePage(isTopLevelParentAPage); assert( page != _pages.end() ); ///retrieve the form layout QGridLayout* layout; if (_useScrollAreasForTabs) { layout = dynamic_cast<QGridLayout*>( dynamic_cast<QScrollArea*>(page->second.tab)->widget()->layout() ); } else { layout = dynamic_cast<QGridLayout*>( page->second.tab->layout() ); } assert(layout); ///if the knob has specified that it didn't want to trigger a new line, decrement the current row /// index of the tab if (!makeNewLine) { --page->second.currentRow; } QWidget* fieldContainer = 0; QHBoxLayout* fieldLayout = 0; if (makeNewLine) { ///if new line is not turned off, create a new line fieldContainer = new QWidget(page->second.tab); fieldLayout = new QHBoxLayout(fieldContainer); fieldLayout->setContentsMargins( TO_DPIX(3), 0, 0, TO_DPIY(NATRON_SETTINGS_VERTICAL_SPACING_PIXELS) ); fieldLayout->setSpacing( TO_DPIY(2) ); fieldLayout->setAlignment(Qt::AlignLeft); } else { ///otherwise re-use the last row's widget and layout assert(lastRowWidget); fieldContainer = lastRowWidget; fieldLayout = dynamic_cast<QHBoxLayout*>( fieldContainer->layout() ); } assert(fieldContainer); assert(fieldLayout); ///Create the label if needed KnobClickableLabel* label = 0; Label* warningLabel = 0; std::string descriptionLabel; KnobString* isStringKnob = dynamic_cast<KnobString*>( knob.get() ); bool isLabelKnob = isStringKnob && isStringKnob->isLabel(); if (isLabelKnob) { descriptionLabel = isStringKnob->getValue(); } else { descriptionLabel = knob->getLabel(); } const std::string& labelIconFilePath = knob->getIconLabel(); QWidget *labelContainer = 0; QHBoxLayout *labelLayout = 0; const bool hasLabel = ret->isLabelVisible() || isLabelKnob; if (hasLabel) { if (makeNewLine) { labelContainer = new QWidget(page->second.tab); labelLayout = new QHBoxLayout(labelContainer); labelLayout->setContentsMargins( TO_DPIX(3), 0, 0, TO_DPIY(NATRON_SETTINGS_VERTICAL_SPACING_PIXELS) ); labelLayout->setSpacing( TO_DPIY(2) ); } label = new KnobClickableLabel(QString(), ret, page->second.tab); warningLabel = new Label(page->second.tab); warningLabel->setVisible(false); QFontMetrics fm(label->font(), 0); int pixSize = fm.height(); QPixmap stdErrorPix; stdErrorPix = getStandardIcon(QMessageBox::Critical, pixSize, label); warningLabel->setPixmap(stdErrorPix); bool pixmapSet = false; if ( !labelIconFilePath.empty() ) { QPixmap pix; if (labelIconFilePath == "dialog-warning") { pix = getStandardIcon(QMessageBox::Warning, pixSize, label); } else if (labelIconFilePath == "dialog-question") { pix = getStandardIcon(QMessageBox::Question, pixSize, label); } else if (labelIconFilePath == "dialog-error") { pix = stdErrorPix; } else if (labelIconFilePath == "dialog-information") { pix = getStandardIcon(QMessageBox::Information, pixSize, label); } else { pix.load( QString::fromUtf8( labelIconFilePath.c_str() ) ); if (pix.width() != pixSize) { pix = pix.scaled(pixSize, pixSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } } if ( !pix.isNull() ) { pixmapSet = true; label->setPixmap(pix); } } if (!pixmapSet) { QString labelStr( QString::fromUtf8( descriptionLabel.c_str() ) ); /*labelStr += ":";*/ if ( ret->isLabelBold() ) { label->setBold(true); } label->setText_overload(labelStr ); } QObject::connect( label, SIGNAL(clicked(bool)), ret.get(), SIGNAL(labelClicked(bool)) ); if (makeNewLine) { labelLayout->addWidget(warningLabel); labelLayout->addWidget(label); } } /* * Find out in which layout the knob should be: either in the layout of the page or in the layout of * the nearest parent group tab in the hierarchy */ boost::shared_ptr<KnobGroup> closestParentGroupTab; KnobPtr parentTmp = parentKnob; assert(parentKnobTmp); while (!closestParentGroupTab) { boost::shared_ptr<KnobGroup> parentGroup = boost::dynamic_pointer_cast<KnobGroup>(parentTmp); if ( parentGroup && parentGroup->isTab() ) { closestParentGroupTab = parentGroup; } parentTmp = parentTmp->getParentKnob(); if (!parentTmp) { break; } } if (closestParentGroupTab) { /* * At this point we know that the parent group (which is a tab in the TabWidget) will have at least 1 knob * so ensure it is added to the TabWidget. * There are 2 possibilities, either the parent of the group tab is another group, in which case we have to * make sure the TabWidget is visible in the parent TabWidget of the group, otherwise we just add the TabWidget * to the on of the page. */ KnobPtr parentParent = closestParentGroupTab->getParentKnob(); KnobGroup* parentParentIsGroup = dynamic_cast<KnobGroup*>( parentParent.get() ); boost::shared_ptr<KnobPage> parentParentIsPage = boost::dynamic_pointer_cast<KnobPage>(parentParent); assert(parentParentIsGroup || parentParentIsPage); if (parentParentIsGroup) { KnobGuiGroup* parentParentGroupGui = dynamic_cast<KnobGuiGroup*>( findKnobGuiOrCreate( parentParent, true, ret->getFieldContainer() ).get() ); assert(parentParentGroupGui); if (parentParentGroupGui) { TabGroup* groupAsTab = parentParentGroupGui->getOrCreateTabWidget(); assert(groupAsTab); layout = groupAsTab->addTab( closestParentGroupTab, QString::fromUtf8( closestParentGroupTab->getLabel().c_str() ) ); } } else if (parentParentIsPage) { PageMap::iterator page = getOrCreatePage(parentParentIsPage); assert( page != _pages.end() ); assert(page->second.groupAsTab); layout = page->second.groupAsTab->addTab( closestParentGroupTab, QString::fromUtf8( closestParentGroupTab->getLabel().c_str() ) ); } assert(layout); } ///fill the fieldLayout with the widgets ret->createGUI(layout, fieldContainer, labelContainer, label, warningLabel, fieldLayout, makeNewLine, knobsOnSameLine); ret->setEnabledSlot(); ///Must add the row to the layout before calling setSecret() if (makeNewLine) { int rowIndex; if (closestParentGroupTab) { rowIndex = layout->rowCount(); } else if ( parentGui && knob->isDynamicallyCreated() ) { const std::list<KnobGuiWPtr>& children = parentGui->getChildren(); if ( children.empty() ) { rowIndex = parentGui->getActualIndexInLayout(); } else { rowIndex = children.back().lock()->getActualIndexInLayout(); } ++rowIndex; } else { rowIndex = page->second.currentRow; } const bool labelOnSameColumn = ret->isLabelOnSameColumn(); if (!hasLabel) { layout->addWidget(fieldContainer, rowIndex, 0, 1, 2); } else { if (label) { if (labelOnSameColumn) { labelLayout->addWidget(fieldContainer); layout->addWidget(labelContainer, rowIndex, 0, 1, 2); } else { layout->addWidget(labelContainer, rowIndex, 0, 1, 1, Qt::AlignRight); layout->addWidget(fieldContainer, rowIndex, 1, 1, 1); } } } //if (closestParentGroupTab) { ///See http://stackoverflow.com/questions/14033902/qt-qgridlayout-automatically-centers-moves-items-to-the-middle for ///a bug of QGridLayout: basically all items are centered, but we would like to add stretch in the bottom of the layout. ///To do this we add an empty widget with an expanding vertical size policy. /*QWidget* foundSpacer = 0; for (int i = 0; i < layout->rowCount(); ++i) { QLayoutItem* item = layout->itemAtPosition(i, 0); if (!item) { continue; } QWidget* w = item->widget(); if (!w) { continue; } if (w->objectName() == QString::fromUtf8("emptyWidget")) { foundSpacer = w; break; } } if (foundSpacer) { layout->removeWidget(foundSpacer); } else { foundSpacer = new QWidget(layout->parentWidget()); foundSpacer->setObjectName(QString::fromUtf8("emptyWidget")); foundSpacer->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); } ///And add our stretch layout->addWidget(foundSpacer,layout->rowCount(), 0, 1, 2);*/ // } } // makeNewLine ret->setSecret(); if ( knob->isNewLineActivated() && ret->shouldAddStretch() ) { fieldLayout->addStretch(); } ///increment the row count ++page->second.currentRow; if (parentIsGroup && parentGui) { parentGui->addKnob(ret); } } // if ( !ret->hasWidgetBeenCreated() && ( !isGroup || !isGroup->isTab() ) ) {
void MyCardsPixmapLabel::setHiddenFrontPixmap ( const QPixmap &pic ) { myHiddenFront = pic.scaled(width(), height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);; }