Exemplo n.º 1
0
void Github::drawCommits()
{
  QFont font;
  font.setPixelSize(16);

  backToRepository = new QPushButton;
  backToRepository->setFont(font);
  backToRepository->setText("back");
  connect(backToRepository, &QPushButton::clicked, this, &Github::backToReposClicked);

  userRepos->setFont(font);

  commits = new QScrollArea;
  commits->setWidgetResizable(true);
  QWidget *w = new QWidget(this);
  w->setLayout(new QVBoxLayout(w));
  commits->setWidget(w);

  QJsonDocument doc = QJsonDocument::fromJson(contentCommits);
  int cnt = 0;
  for (auto json : doc.array())
  {
    QString name = json.toObject()["commit"].toObject()["author"].toObject()["name"].toString();
    QString sha = json.toObject()["sha"].toString();
    QString date = json.toObject()["commit"].toObject()["author"].toObject()["date"].toString();
    QString comment = json.toObject()["commit"].toObject()["message"].toString();

    QString imageAddress = json.toObject()["author"].toObject()["avatar_url"].toString();

    QLabel *nameLabel = new QLabel("Author: " + name);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QLabel *shaLabel = new QLabel("Hash: " + sha);
    shaLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QLabel *dateLabel = new QLabel("Date: " + date);
    dateLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QLabel *commentLabel = new QLabel("Comment: " + comment);
    commentLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    QWidget *commit = new QWidget;

    QPixmap image;
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(imageAddress)));
    connect(reply, &QNetworkReply::finished, this, &Github::loadPicture);
    loaderImage[reply] = commit;

    QLayout *lay = new QGridLayout;
    commit->setLayout(lay);

    commit->layout()->addWidget(nameLabel);
    commit->layout()->addWidget(shaLabel);
    commit->layout()->addWidget(dateLabel);
    commit->layout()->addWidget(commentLabel);

    w->layout()->addWidget(commit);
    cnt++;
  }

  ui->gridLayout->addWidget(backToRepository, 0, 0);
  ui->gridLayout->addWidget(userRepos, 2, 0);
  ui->gridLayout->addWidget(commits, 3, 0);
}
Exemplo n.º 2
0
void SGI_SymbolPin::paint(QPainter*                       painter,
                          const QStyleOptionGraphicsItem* option,
                          QWidget*                        widget) {
  Q_UNUSED(widget);
  const bool deviceIsPrinter =
      (dynamic_cast<QPrinter*>(painter->device()) != 0);
  const qreal lod =
      option->levelOfDetailFromTransform(painter->worldTransform());

  const NetSignal* netsignal = mPin.getCompSigInstNetSignal();
  bool             highlight =
      mPin.isSelected() || (netsignal && netsignal->isHighlighted());

  // draw line
  GraphicsLayer* layer = getLayer(GraphicsLayer::sSymbolOutlines);
  Q_ASSERT(layer);
  if (layer->isVisible()) {
    painter->setPen(QPen(layer->getColor(highlight), Length(158750).toPx(),
                         Qt::SolidLine, Qt::RoundCap));
    painter->drawLine(QPointF(0, 0),
                      Point(*mLibPin.getLength(), 0).toPxQPointF());
  }

  // draw circle
  if (mPin.isRequired()) {
    layer = getLayer(GraphicsLayer::sSymbolPinCirclesReq);
  } else {
    layer = getLayer(GraphicsLayer::sSymbolPinCirclesOpt);
  }
  Q_ASSERT(layer);
  if ((layer->isVisible()) && (!deviceIsPrinter) && (!netsignal)) {
    painter->setPen(QPen(layer->getColor(highlight), 0));
    painter->setBrush(Qt::NoBrush);
    painter->drawEllipse(QPointF(0, 0), mRadiusPx, mRadiusPx);
  }

  // fill circle
  if (mIsVisibleJunction && mJunctionLayer && mJunctionLayer->isVisible()) {
    painter->setPen(QPen(mJunctionLayer->getColor(highlight), 0));
    painter->setBrush(mJunctionLayer->getColor(highlight));
    painter->drawEllipse(QPointF(0, 0), mRadiusPx, mRadiusPx);
  }

  // draw text or filled rect
  layer = getLayer(GraphicsLayer::sSymbolPinNames);
  Q_ASSERT(layer);
  if ((layer->isVisible()) && (!mStaticText.text().isEmpty())) {
    if ((deviceIsPrinter) || (lod > 1)) {
      // draw text
      painter->save();
      if (mMirrored) {
        static const QTransform gMirror(-1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
        painter->setTransform(gMirror, true);
      }
      if (mRotate180) painter->rotate(180);
      painter->setPen(QPen(layer->getColor(highlight), 0));
      painter->setFont(mFont);
      painter->drawStaticText(mTextOrigin, mStaticText);
      painter->restore();
    } else {
      // draw filled rect
      painter->setPen(Qt::NoPen);
      painter->setBrush(QBrush(layer->getColor(highlight), Qt::Dense5Pattern));
      painter->drawRect(mTextBoundingRect);
    }
  }

#ifdef QT_DEBUG
  layer = getLayer(GraphicsLayer::sDebugSymbolPinNetSignalNames);
  Q_ASSERT(layer);
  if ((layer->isVisible()) && (netsignal)) {
    // draw net signal name
    QFont font = qApp->getDefaultMonospaceFont();
    font.setPixelSize(3);
    painter->setFont(font);
    painter->setPen(QPen(layer->getColor(highlight), 0));
    painter->save();
    if (mRotate180) painter->rotate(180);
    painter->drawText(QRectF(),
                      Qt::AlignHCenter | Qt::AlignBottom | Qt::TextSingleLine |
                          Qt::TextDontClip,
                      *netsignal->getName());
    painter->restore();
  }
  layer = getLayer(GraphicsLayer::sDebugGraphicsItemsBoundingRects);
  Q_ASSERT(layer);
  if (layer->isVisible()) {
    // draw bounding rect
    painter->setPen(QPen(layer->getColor(highlight), 0));
    painter->setBrush(Qt::NoBrush);
    painter->drawRect(mBoundingRect);
  }
  layer = getLayer(GraphicsLayer::sDebugGraphicsItemsTextsBoundingRects);
  Q_ASSERT(layer);
  if (layer->isVisible()) {
    // draw text bounding rect
    painter->setPen(QPen(layer->getColor(highlight), 0));
    painter->setBrush(Qt::NoBrush);
    painter->drawRect(mTextBoundingRect);
  }
#endif
}
Exemplo n.º 3
0
void WzMainWindow::setFontSize(float size)
{
	QFont theFont = font();
	theFont.setPixelSize(size);
	setFont(theFont);
}
Exemplo n.º 4
0
void GameFrame::paintEvent(QPaintEvent *) {
    if (!active) {
        return;
    }

    int rows = 9;
    int cols = 9;

    int window_width = geometry().size().width();
    int window_height = geometry().size().height();

    int width = window_width / cols;
    int height = window_height / rows;

    QPainter painter(this);

    QBrush brush(Qt::SolidPattern);

    int fontSize = 30;
    if (window_width < 500 || window_height < 500) {
        fontSize = 12;
    }

    int noteFontSize = 10;

    QFont font("Ubuntu", fontSize);
    painter.setFont(font);
    painter.setRenderHint(QPainter::Antialiasing);

    QFont fontNotes = font;
    fontNotes.setPixelSize(noteFontSize);

    std::map<int, bool> otherFocus;
    if (!playersFocus.empty()) {
        for (auto f : playersFocus) {
            if (f.second > -1) {
                otherFocus[f.second] = true;
            }
        }
    }

    QPen pen;

    for (int row = 0; row < rows; ++row) {
        for (int col = 0; col < cols; ++col) {
            int pos = row * rows + col;
            QRect rect(col * width, row * height, width, height);
            int valueGiven = this->getGivenAt(pos);
            int value = this->getAt(pos);

            QColor bg;
            QColor fg;

            if (valueGiven > 0) {
                bg = colors.given_background;
                fg = colors.given_foreground;
            } else if (pos == focused) {
                bg = colors.focus_background;
                fg = colors.focus_foreground;
            } else if (value > 0) {
                bg = colors.filled_background;
                fg = colors.filled_foreground;
            } else if (otherFocus[pos]) {
                bg = colors.other_focus_background;
                fg = colors.other_focus_foreground;
            } else {
                bg = colors.background;
                fg = colors.foreground;
            }

            pen.setColor(fg);
            painter.fillRect(rect, bg);
            painter.setPen(pen);

            std::vector<int> &notes_pos = notes[pos];
            if (notesEnabled && !notes_pos.empty()) {
                painter.setFont(fontNotes);
                for (auto note : notes_pos) {
                    QString text = QString::number(note);
                    note--;
                    int note_width = width / 3;
                    int note_height = height / 3;
                    int note_pos_x = note % 3;
                    int note_pos_y = note / 3;

                    int note_x = rect.x() + (note_pos_x * note_width);
                    int note_y = rect.y() + (note_pos_y * note_height);

                    QRect rect_note(note_x, note_y, note_width, note_height);
                    painter.drawText(rect_note, Qt::AlignVCenter | Qt::AlignCenter, text);
                }

            } else if (value > 0) {
                painter.setFont(font);
                QString text = QString::number(value);
                painter.drawText(rect, Qt::AlignVCenter | Qt::AlignCenter, text);
            }
        }
    }

    QPen outer_lines;
    outer_lines.setColor(colors.outer_lines);
    outer_lines.setWidth(5);

    QPen inner_lines;
    inner_lines.setColor(colors.inner_lines);
    inner_lines.setWidth(1);

    for (int i = 0; i <= rows; ++i) {
        painter.setPen(inner_lines);
        if (i % 3 == 0) {
            painter.setPen(outer_lines);
        }
        painter.drawLine(width * i, 0, width * i, height * rows);
    }

    for (int i = 0; i <= cols; ++i) {
        painter.setPen(inner_lines);
        if (i % 3 == 0) {
            painter.setPen(outer_lines);
        }
        painter.drawLine(0, height * i, width * cols, height * i);
    }
}
Exemplo n.º 5
0
void tst_QFont::serialize_data()
{
    QTest::addColumn<QFont>("font");
    // The version in which the tested feature was added.
    QTest::addColumn<QDataStream::Version>("minimumStreamVersion");

    QFont basicFont;
    // Versions <= Qt 2.1 had broken point size serialization,
    // so we set an integer point size.
    basicFont.setPointSize(9);

    QFont font = basicFont;
    QTest::newRow("defaultConstructed") << font << QDataStream::Qt_1_0;

    font.setLetterSpacing(QFont::AbsoluteSpacing, 105);
    QTest::newRow("letterSpacing") << font << QDataStream::Qt_4_5;

    font = basicFont;
    font.setWordSpacing(50.0);
    QTest::newRow("wordSpacing") << font << QDataStream::Qt_4_5;

    font = basicFont;
    font.setPointSize(20);
    QTest::newRow("pointSize") << font << QDataStream::Qt_1_0;

    font = basicFont;
    font.setPixelSize(32);
    QTest::newRow("pixelSize") << font << QDataStream::Qt_3_0;

    font = basicFont;
    font.setStyleHint(QFont::Monospace);
    QTest::newRow("styleHint") << font << QDataStream::Qt_1_0;

    font = basicFont;
    font.setStretch(4000);
    QTest::newRow("stretch") << font << QDataStream::Qt_4_3;

    font = basicFont;
    font.setWeight(99);
    QTest::newRow("weight") << font << QDataStream::Qt_1_0;

    font = basicFont;
    font.setUnderline(true);
    QTest::newRow("underline") << font << QDataStream::Qt_1_0;

    font = basicFont;
    font.setStrikeOut(true);
    QTest::newRow("strikeOut") << font << QDataStream::Qt_1_0;

    font = basicFont;
    font.setFixedPitch(true);
    // This fails for versions less than this, as ignorePitch is set to false
    // whenever setFixedPitch() is called, but ignorePitch is considered an
    // extended bit, which were apparently not available until 4.4.
    QTest::newRow("fixedPitch") << font << QDataStream::Qt_4_4;

    font = basicFont;
    font.setLetterSpacing(QFont::AbsoluteSpacing, 10);
    // Fails for 4.4 because letterSpacing wasn't read until 4.5.
    QTest::newRow("letterSpacing") << font << QDataStream::Qt_4_5;

    font = basicFont;
    font.setRawMode(true);
    QTest::newRow("rawMode") << font << QDataStream::Qt_1_0;

    font = basicFont;
    font.setKerning(false);
    QTest::newRow("kerning") << font << QDataStream::Qt_4_0;

    font = basicFont;
    font.setStyleStrategy(QFont::NoFontMerging);
    // This wasn't read properly until 5.4.
    QTest::newRow("styleStrategy") << font << QDataStream::Qt_5_4;

    font = basicFont;
    font.setHintingPreference(QFont::PreferFullHinting);
    // This wasn't read until 5.4.
    QTest::newRow("hintingPreference") << font << QDataStream::Qt_5_4;

    font = basicFont;
    font.setStyleName("Regular Black Condensed");
    // This wasn't read until 5.4.
    QTest::newRow("styleName") << font << QDataStream::Qt_5_4;
}
Exemplo n.º 6
0
void
Style::drawDial(const QStyleOptionComplex *option, QPainter *painter, const QWidget *) const
{
    ASSURE_OPTION(dial, Slider);

    OPT_ENABLED OPT_HOVER OPT_FOCUS
    SAVE_PAINTER(Pen|Brush|Alias|Font);

    QRect rect = RECT;
    if (rect.width() > rect.height()) {
        rect.setLeft(rect.x()+(rect.width()-rect.height())/2);
        rect.setWidth(rect.height());
    } else {
        rect.setTop(rect.y()+(rect.height()-rect.width())/2);
        rect.setHeight(rect.width());
    }

    int d = qMin(2*rect.width()/5, config.slider.thickness);
    int r = (rect.width()-d)/2;

    // angle calculation from qcommonstyle.cpp (c) Trolltech 1992-2007, ASA.
    float a;
    if (dial->maximum == dial->minimum)
        a = M_PI / 2;
    else if (dial->dialWrapping)
        a = M_PI * 3 / 2 - (dial->sliderValue - dial->minimum) * 2 * M_PI / (dial->maximum - dial->minimum);
    else
        a = (M_PI * 8 - (dial->sliderValue - dial->minimum) * 10 * M_PI / (dial->maximum - dial->minimum)) / 6;

    QPoint cp = rect.center() + QPoint(qRound(r * cos(a)), -qRound(r * sin(a)));

    // the huge ring =======================================
    r = d/2+1; rect.adjust(r,r,-r,-r);

    painter->setBrush(Qt::NoBrush);
    painter->setRenderHint( QPainter::Antialiasing );
    const int start = -(dial->dialWrapping ? 90 : 120)*16;
    const int span = -16*(dial->dialWrapping ? 360 : 300)*(dial->sliderValue - dial->minimum)/(dial->maximum - dial->minimum);
    QPen pen;
    if (dial->sliderValue != dial->maximum) {
        QPen pen(GROOVE_COLOR, d);
        pen.setCapStyle(Qt::RoundCap);
        painter->setPen(pen);
        painter->drawArc(rect, start + span, -((dial->dialWrapping ? 360 : 300)*16 + span));
    }
    if (dial->sliderValue != dial->minimum) {
        QPen pen(THERMOMETER_COLOR, d - 2*(d/THERMOMETER_FACTOR));
        pen.setCapStyle(Qt::RoundCap);
        painter->setPen(pen);
        painter->drawArc(rect, start, span);
    }

    // the value ==============================================
    QFont fnt = painter->font();
    int h = rect.height()/2;
    h -= 2 * (h - qMin(h, painter->fontMetrics().xHeight())) / 3;
    fnt.setPixelSize( h );
    painter->setFont(fnt);
    painter->setPen(FX::blend(PAL.background().color(), PAL.foreground().color(),!hasFocus,2));
    drawItemText(painter, rect,  Qt::AlignCenter, PAL, isEnabled, QString::number(dial->sliderValue));

    // the drop ===========================
    if (isEnabled) {
        rect = QRect(0,0,d,d);
        rect.moveCenter(cp);
        drawSliderHandle(rect, option, painter, hover * 6);
    }

    RESTORE_PAINTER
}
Exemplo n.º 7
0
/*
 * Let us pre-render the tiles. Either we've a Custom Image as
 * background or we use the drawRect  to fill the background and
 * last we put the number on it
 */
void PiecesTable::slotCustomImage( const QString& _str ) {
    QString str = _str;


    /* couldn't load image fall back to plain tiles*/
    QImage img = QImage(str);
    QPixmap pix;
    if(img.isNull())
        str = QString::null;
    else{
        img = img.smoothScale( width(),height() );
        pix.convertFromImage( img );
    }

    /* initialize base point */
    uint image=0;

    /* clear the old tiles */
    clear();

    /* used variables */
    int cols = numCols();
    int rows = numRows();
    int cellW   = cellWidth();
    int cellH   = cellHeight();
    int x2      = cellW-1;
    int y2      = cellH-1;
    bool empty  = str.isEmpty();
    double bw      = empty ? 0.9 : 0.98;
    int	x_offset = cellW - int(cellW * bw);	// 10% should be enough
    int	y_offset = cellH - int(cellH * bw);

    /* border polygon calculation*/
    initPolygon(cellW, cellH, x_offset, y_offset );

    /* avoid crashes with isNull() pixmap later */
    if ( cellW == 0 || cellH == 0 ) {
        _pixmap.resize( 0 );
        return;
    }

    /* make it bold and bigger */
    QFont f = font();
    f.setPixelSize(18);
    f.setBold( TRUE );

    /* for every tile */
    for(int row = 0; row < rows; ++row ) {
        for(int col= 0; col < cols; ++col) {
            QPixmap *pip = new QPixmap(cellW, cellH );
            QPainter *p = new QPainter(pip );
            p->setFont( f );

            /* draw the tradional tile  or a part of the pixmap*/
            if(empty) {
                p->setBrush(_colors[image]);
                p->setPen(NoPen);
                p->drawRect(0,0,cellW,cellH);
            }else
                p->drawPixmap(0, 0, pix,col*cellW, row*cellH, cellW, cellH );

            // draw borders
            if (height() > 40) {
                p->setBrush(_colors[image].light(130));
                p->drawPolygon(light_border);

                p->setBrush(_colors[image].dark(130));
                p->drawPolygon(dark_border);
            }

            // draw number
            p->setPen(black);
            p->drawText(0, 0, x2, y2, AlignHCenter | AlignVCenter, QString::number(image+1));

            delete p;
            _pixmap[image++] =  pip;
        }
    }
    _image = str;
}
Exemplo n.º 8
0
int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
	//  Enable standard input/output on Windows Platform for debug
	BOOL consoleAttached = ::AttachConsole(ATTACH_PARENT_PROCESS);
	if (consoleAttached) {
		freopen("CON", "r", stdin);
		freopen("CON", "w", stdout);
		freopen("CON", "w", stderr);
	}
#endif

	/*-- "-layout [レイアウト設定ファイル名]" で、必要なモジュールのPageだけのレイアウトで起動することを可能にする --*/
	QString argumentLayoutFileName = "";
	TFilePath loadScenePath;
	if (argc > 1) {
		for (int a = 1; a < argc; a++) {
			if (QString(argv[a]) == "-layout") {
				argumentLayoutFileName = QString(argv[a + 1]);
				a++;
			} else
				loadScenePath = TFilePath(argv[a]);
		}
	}

	QApplication a(argc, argv);

#ifdef Q_OS_WIN
	//	Since currently OpenToonz does not work with OpenGL of software or angle,
	//	force Qt to use desktop OpenGL
	a.setAttribute(Qt::AA_UseDesktopOpenGL, true);
#endif

	// Some Qt objects are destroyed badly withouth a living qApp. So, we must enforce a way to either
	// postpone the application destruction until the very end, OR ensure that sensible objects are
	// destroyed before.

	// Using a static QApplication only worked on Windows, and in any case C++ respects the statics destruction
	// order ONLY within the same library. On MAC, it made the app crash on exit o_o. So, nope.

	std::auto_ptr<QObject> mainScope(new QObject(&a)); // A QObject destroyed before the qApp is therefore explicitly
	mainScope->setObjectName("mainScope");			   // provided. It can be accessed by looking in the qApp's children.

#ifdef _WIN32
#ifndef x64
	//Store the floating point control word. It will be re-set before Toonz initialization
	//has ended.
	unsigned int fpWord = 0;
	_controlfp_s(&fpWord, 0, 0);
#endif
#endif

#ifdef _WIN32
	//At least on windows, Qt's 4.5.2 native windows feature tend to create
	//weird flickering effects when dragging panel separators.
	a.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#endif

	//Set the app's locale for numeric stuff to standard C. This is important for atof() and similar
	//calls that are locale-dependant.
	setlocale(LC_NUMERIC, "C");

// Set current directory to the bundle/application path - this is needed to have correct relative paths
#ifdef MACOSX
	{
		QDir appDir(QApplication::applicationDirPath());
		appDir.cdUp(), appDir.cdUp(), appDir.cdUp();

		bool ret = QDir::setCurrent(appDir.absolutePath());
		assert(ret);
	}
#endif

	// splash screen
	QPixmap splashPixmap(":Resources/splash.png");
#ifdef _WIN32
	a.setFont(QFont("Arial", 10));
#else
	a.setFont(QFont("Helvetica", 10));
#endif

	QString offsetStr("\n\n\n\n\n\n\n\n");

	TSystem::hasMainLoop(true);

	TMessageRepository::instance();

	QSplashScreen splash(splashPixmap);
	splash.show();
	a.processEvents();

	splash.showMessage(offsetStr + "Initializing QGLFormat...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// OpenGL
	QGLFormat fmt;
	fmt.setAlpha(true);
	fmt.setStencil(true);
	QGLFormat::setDefaultFormat(fmt);

#ifdef LINUX
	glutInit(&argc, argv);
#endif

	splash.showMessage(offsetStr + "Initializing Toonz environment ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	//Install run out of contiguous memory callback
	TBigMemoryManager::instance()->setRunOutOfContiguousMemoryHandler(&toonzRunOutOfContMemHandler);

	// Toonz environment
	initToonzEnv();

	// Initialize thread components
	TThread::init();

	TProjectManager *projectManager = TProjectManager::instance();
	if (Preferences::instance()->isSVNEnabled()) {
		// Read Version Control repositories and add it to project manager as "special" svn project root
		VersionControl::instance()->init();
		QList<SVNRepository> repositories = VersionControl::instance()->getRepositories();
		int count = repositories.size();
		for (int i = 0; i < count; i++) {
			SVNRepository r = repositories.at(i);

			TFilePath localPath(r.m_localPath.toStdWString());
			if (!TFileStatus(localPath).doesExist()) {
				try {
					TSystem::mkDir(localPath);
				} catch (TException &e) {
					fatalError(QString::fromStdWString(e.getMessage()));
				}
			}
			projectManager->addSVNProjectsRoot(localPath);
		}
	}

#if defined(MACOSX) && defined(__LP64__)

	//Load the shared memory settings
	int shmmax = Preferences::instance()->getShmMax();
	int shmseg = Preferences::instance()->getShmSeg();
	int shmall = Preferences::instance()->getShmAll();
	int shmmni = Preferences::instance()->getShmMni();

	if (shmall < 0) //Make sure that at least 100 MB of shared memory are available
		shmall = (tipc::shm_maxSharedPages() < (100 << 8)) ? (100 << 8) : -1;

	tipc::shm_set(shmmax, shmseg, shmall, shmmni);

#endif

	// DVDirModel must be instantiated after Version Control initialization...
	FolderListenerManager::instance()->addListener(DvDirModel::instance());

	splash.showMessage(offsetStr + "Loading Translator ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// Carico la traduzione contenuta in toonz.qm (se � presente)
	QString languagePathString = QString::fromStdString(toString(TEnv::getConfigDir() + "loc"));
#ifndef WIN32
	//the merge of menu on osx can cause problems with different languages with the Preferences menu
	//qt_mac_set_menubar_merge(false);
	languagePathString += "/" + Preferences::instance()->getCurrentLanguage();
#else
	languagePathString += "\\" + Preferences::instance()->getCurrentLanguage();
#endif
	QTranslator translator;
#ifdef LINETEST
	translator.load("linetest", languagePathString);
#else
	translator.load("toonz", languagePathString);
#endif

	// La installo
	a.installTranslator(&translator);

	// Carico la traduzione contenuta in toonzqt.qm (se e' presente)
	QTranslator translator2;
	translator2.load("toonzqt", languagePathString);
	a.installTranslator(&translator2);

	// Carico la traduzione contenuta in tnzcore.qm (se e' presente)
	QTranslator tnzcoreTranslator;
	tnzcoreTranslator.load("tnzcore", languagePathString);
	qApp->installTranslator(&tnzcoreTranslator);

	// Carico la traduzione contenuta in toonzlib.qm (se e' presente)
	QTranslator toonzlibTranslator;
	toonzlibTranslator.load("toonzlib", languagePathString);
	qApp->installTranslator(&toonzlibTranslator);

	// Carico la traduzione contenuta in colorfx.qm (se e' presente)
	QTranslator colorfxTranslator;
	colorfxTranslator.load("colorfx", languagePathString);
	qApp->installTranslator(&colorfxTranslator);

	// Carico la traduzione contenuta in tools.qm
	QTranslator toolTranslator;
	toolTranslator.load("tnztools", languagePathString);
	qApp->installTranslator(&toolTranslator);

	// Aggiorno la traduzione delle properties di tutti i tools
	TTool::updateToolsPropertiesTranslation();

	splash.showMessage(offsetStr + "Loading styles ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// stile
	QApplication::setStyle("windows");

	IconGenerator::setFilmstripIconSize(Preferences::instance()->getIconSize());

	splash.showMessage(offsetStr + "Loading shaders ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	loadShaderInterfaces(ToonzFolder::getLibraryFolder() + TFilePath("shaders"));

	splash.showMessage(offsetStr + "Initializing Toonz application ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	TTool::setApplication(TApp::instance());
	TApp::instance()->init();

//iwsw commented out temporarily
#if 0 
  QStringList monitorNames;
  /*-- 接続モニタがPVM-2541の場合のみLUTを読み込む --*/
  if (Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
  {
	  /*-- 接続モニタがPVM-2541の場合のみLUTを読み込む --*/
	  monitorNames = Ghibli3DLutUtil::getMonitorName();
	  if (monitorNames.contains(QString::fromStdWString(L"PVM-2541")))
		  /*-- 3DLUTファイルを読み込む --*/
		  Ghibli3DLutUtil::loadLutFile(Preferences::instance()->get3DLutPath());
  }
  /*-- 接続モニタをスプラッシュ画面にも表示 --*/
  if (!monitorNames.isEmpty())
  {
	  lastUpdateStr += QString("Monitor Name : ");
	  for (int mn = 0; mn < monitorNames.size(); mn++)
	  {
		  if (mn != 0)
			  lastUpdateStr += QString(", ");
		  lastUpdateStr += monitorNames.at(mn);
	  }
	  lastUpdateStr += QString("\n");
  }
#endif

	splash.showMessage(offsetStr + "Loading Plugins...", Qt::AlignCenter, Qt::white);
	a.processEvents();
	/* poll the thread ends: 
	 絶対に必要なわけではないが PluginLoader は中で setup ハンドラが常に固有のスレッドで呼ばれるよう main thread queue の blocking をしているので
	 processEvents を行う必要がある
   */
	while (!PluginLoader::load_entries("")) {
		a.processEvents();
	}

	splash.showMessage(offsetStr + "Creating main window ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	/*-- Layoutファイル名をMainWindowのctorに渡す --*/
	MainWindow w(argumentLayoutFileName);

	splash.showMessage(offsetStr + "Loading style sheet ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// Carico lo styleSheet
	QString currentStyle = Preferences::instance()->getCurrentStyleSheet();
	a.setStyleSheet(currentStyle);

	TApp::instance()->setMainWindow(&w);
	w.setWindowTitle(applicationFullName);

	splash.showMessage(offsetStr + "Starting main window ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	TFilePath fp = ToonzFolder::getModuleFile("mainwindow.ini");
	QSettings settings(toQString(fp), QSettings::IniFormat);
	w.restoreGeometry(settings.value("MainWindowGeometry").toByteArray());

#ifndef MACOSX
	//Workaround for the maximized window case: Qt delivers two resize events, one in the normal geometry, before
	//maximizing (why!?), the second afterwards - all inside the following show() call. This makes troublesome for
	//the docking system to correctly restore the saved geometry. Fortunately, MainWindow::showEvent(..) gets called
	//just between the two, so we can disable the currentRoom layout right before showing and re-enable it after
	//the normal resize has happened.
	if (w.isMaximized())
		w.getCurrentRoom()->layout()->setEnabled(false);
#endif

	QRect splashGeometry = splash.geometry();
	splash.finish(&w);

	a.setQuitOnLastWindowClosed(false);
// a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
	w.checkForUpdates();

	w.show();

	//Show floating panels only after the main window has been shown
	w.startupFloatingPanels();

	CommandManager::instance()->execute(T_Hand);
	if (!loadScenePath.isEmpty()) {
		splash.showMessage(QString("Loading file '") + loadScenePath.getQString() + "'...", Qt::AlignCenter, Qt::white);

		loadScenePath = loadScenePath.withType("tnz");
		if (TFileStatus(loadScenePath).doesExist())
			IoCmd::loadScene(loadScenePath);
	}

	QFont *myFont;

	std::string family = EnvSoftwareCurrentFont;
	myFont = new QFont(QString(family.c_str()));

	myFont->setPixelSize(EnvSoftwareCurrentFontSize);
	/*-- フォントのBoldの指定 --*/
	std::string weight = EnvSoftwareCurrentFontWeight;
	if (strcmp(weight.c_str(), "Yes") == 0)
		myFont->setBold(true);
	else
		myFont->setBold(false);
	a.setFont(*myFont);

	QAction *action = CommandManager::instance()->getAction("MI_OpenTMessage");
	if (action)
		QObject::connect(TMessageRepository::instance(), SIGNAL(openMessageCenter()), action, SLOT(trigger()));

	QObject::connect(
		TUndoManager::manager(), SIGNAL(somethingChanged()),
		TApp::instance()->getCurrentScene(), SLOT(setDirtyFlag()));

#ifdef _WIN32
#ifndef x64
	//On 32-bit architecture, there could be cases in which initialization could alter the
	//FPU floating point control word. I've seen this happen when loading some AVI coded (VFAPI),
	//where 80-bit internal precision was used instead of the standard 64-bit (much faster and
	//sufficient - especially considering that x86 truncates to 64-bit representation anyway).
	//IN ANY CASE, revert to the original control word.
	//In the x64 case these precision changes simply should not take place up to _controlfp_s
	//documentation.
	_controlfp_s(0, fpWord, -1);
#endif
#endif

	a.installEventFilter(TApp::instance());

	int ret = a.exec();

	TUndoManager::manager()->reset();
	PreviewFxManager::instance()->reset();

#ifdef _WIN32
	if (consoleAttached) {
		::FreeConsole();
	}
#endif

	return ret;
}
Exemplo n.º 9
0
void
AlbumItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    PlayableItem* item = m_model->sourceModel()->itemFromIndex( m_model->mapToSource( index ) );
    if ( !item )
        return;

    QStyleOptionViewItemV4 opt = option;
    initStyleOption( &opt, QModelIndex() );
    qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter );

    painter->save();
    painter->setRenderHint( QPainter::Antialiasing );

    QRect r = option.rect;
    QString top, bottom;
    if ( !item->album().isNull() )
    {
        top = item->album()->name();

        if ( !item->album()->artist().isNull() )
            bottom = item->album()->artist()->name();
    }
    else if ( !item->artist().isNull() )
    {
        top = item->artist()->name();
    }
    else
    {
        top = item->query()->track();
        bottom = item->query()->artist();
    }

    if ( !m_covers.contains( index ) )
    {
        if ( !item->album().isNull() )
        {
            m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->album(), r.size(), TomahawkUtils::Grid ) ) );
        }
        else if ( !item->artist().isNull() )
        {
            m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->artist(), r.size(), TomahawkUtils::Grid ) ) );
        }
        else
        {
            m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->query(), r.size(), TomahawkUtils::Grid ) ) );
        }

        _detail::Closure* closure = NewClosure( m_covers[ index ], SIGNAL( repaintRequest() ), const_cast<AlbumItemDelegate*>(this), SLOT( doUpdateIndex( QPersistentModelIndex ) ), QPersistentModelIndex( index ) );
        closure->setAutoDelete( false );
    }

    QSharedPointer< Tomahawk::PixmapDelegateFader > fader = m_covers[ index ];
    if ( fader->size() != r.size() )
        fader->setSize( r.size() );

    const QPixmap cover = fader->currentPixmap();
    painter->drawPixmap( r, cover );

    qreal opacity = -1.;
    if ( m_hoverFaders.contains( index ) )
    {
        const qreal pct = ( m_hoverFaders[ index ]->currentFrame() / 100. );
        opacity = 0.35 - pct * 0.35;
    }
    else if ( m_hoverIndex == index )
    {
        opacity = 0.35;
    }

    if ( opacity > -1. )
    {
        painter->save();

        painter->setPen( QColor( 33, 33, 33 ) );
        painter->setBrush( QColor( 33, 33, 33 ) );
        painter->setOpacity( opacity );
        painter->drawRect( r );

        painter->restore();
    }

    painter->save();

    painter->setPen( Qt::black );
    painter->setBrush( Qt::black );
    painter->setOpacity( 0.5 );
    painter->drawRoundedRect( r.adjusted( 4, +r.height() - 36, -4, -4 ), 3, 3 );

    painter->restore();

    painter->setPen( opt.palette.color( QPalette::HighlightedText ) );
    QTextOption to;
    to.setWrapMode( QTextOption::NoWrap );

    QString text;
    QFont font = opt.font;
    font.setPixelSize( 10 );
    QFont boldFont = font;
    boldFont.setBold( true );
    boldFont.setPixelSize( 14 );

    QRect textRect = option.rect.adjusted( 6, option.rect.height() - 36, -4, -6 );
    painter->setFont( font );
    int bottomHeight = painter->fontMetrics().boundingRect( bottom ).height();
    painter->setFont( boldFont );
    int topHeight = painter->fontMetrics().boundingRect( top ).height();

    bool oneLiner = false;
    if ( bottom.isEmpty() )
        oneLiner = true;
    else
        oneLiner = ( textRect.height() < topHeight + bottomHeight );

    if ( oneLiner )
    {
        to.setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
        text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 );
        painter->drawText( textRect, text, to );
    }
    else
    {
        to.setAlignment( Qt::AlignHCenter | Qt::AlignTop );
        text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 );
        painter->drawText( textRect, text, to );

        painter->setFont( font );
        // If the user is hovering over an artist rect, draw a background so she knows it's clickable
        QRect r = textRect;
        r.setTop( r.bottom() - painter->fontMetrics().height() );
        r.adjust( 4, 0, -4, -1 );
        if ( m_hoveringOver == index )
        {
            TomahawkUtils::drawQueryBackground( painter, opt.palette, r, 1.1 );
            painter->setPen( opt.palette.color( QPalette::HighlightedText ) );
        }

        to.setAlignment( Qt::AlignHCenter | Qt::AlignBottom );
        text = painter->fontMetrics().elidedText( bottom, Qt::ElideRight, textRect.width() - 10 );
        painter->drawText( textRect.adjusted( 5, -1, -5, -1 ), text, to );

        // Calculate rect of artist on-hover button click area
        m_artistNameRects[ index ] = r;
    }

    painter->restore();
}
Exemplo n.º 10
0
void
PlaylistChartItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    PlayableItem* item = m_model->itemFromIndex( m_model->mapToSource( index ) );
    Q_ASSERT( item );

    QStyleOptionViewItemV4 opt = option;
    prepareStyleOption( &opt, index, item );
    opt.text.clear();

    qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter );

    if ( m_view->header()->visualIndex( index.column() ) > 0 )
        return;

    const query_ptr q = item->query()->displayQuery();
    unsigned int duration = q->duration();
    QString artist = q->artist();
    QString track = q->track();
    QPixmap avatar;
    QString upperText, lowerText;

    painter->save();
    {
        QRect r = opt.rect.adjusted( 3, 6, 0, -6 );

        // Paint Now Playing Speaker Icon
        if ( item->isPlaying() )
        {
            QPixmap nowPlayingIcon = TomahawkUtils::defaultPixmap( TomahawkUtils::NowPlayingSpeaker );
            QRect npr = r.adjusted( 3, r.height() / 2 - nowPlayingIcon.height() / 2, 18 - r.width(), -r.height() / 2 + nowPlayingIcon.height() / 2 );
            nowPlayingIcon = TomahawkUtils::defaultPixmap( TomahawkUtils::NowPlayingSpeaker, TomahawkUtils::Original, npr.size() );
            painter->drawPixmap( npr, nowPlayingIcon );
            r.adjust( 22, 0, 0, 0 );
        }

        QFont figureFont = opt.font;
        figureFont.setPixelSize( 18 );
        figureFont.setWeight( 99 );

        QFont boldFont = opt.font;
        boldFont.setPixelSize( 15 );
        boldFont.setWeight( 99 );

        QFont smallBoldFont = opt.font;
        smallBoldFont.setPixelSize( 12 );
        smallBoldFont.setWeight( 60 );

        QFont durationFont = opt.font;
        durationFont.setPixelSize( 12 );
        durationFont.setWeight( 80 );

        if ( index.row() == 0 )
        {
            figureFont.setPixelSize( 36 );
            boldFont.setPixelSize( 26 );
            smallBoldFont.setPixelSize( 22 );
        }
        else if ( index.row() == 1 )
        {
            figureFont.setPixelSize( 30 );
            boldFont.setPixelSize( 22 );
            smallBoldFont.setPixelSize( 18 );
        }
        else if ( index.row() == 2 )
        {
            figureFont.setPixelSize( 24 );
            boldFont.setPixelSize( 18 );
            smallBoldFont.setPixelSize( 14 );
        }
        else if ( index.row() >= 10 )
        {
            boldFont.setPixelSize( 12 );
            smallBoldFont.setPixelSize( 11 );
        }

        QRect figureRect = r.adjusted( 0, 0, -option.rect.width() + 60 - 6 + r.left(), 0 );
        painter->setFont( figureFont );
        painter->setPen( option.palette.text().color().lighter( 450 ) );
        painter->drawText( figureRect, QString::number( index.row() + 1 ), m_centerOption );
        painter->setPen( opt.palette.text().color() );

        QRect pixmapRect = r.adjusted( figureRect.width() + 6, 0, -option.rect.width() + figureRect.width() + option.rect.height() - 6 + r.left(), 0 );

        if ( !m_pixmaps.contains( index ) )
        {
            m_pixmaps.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->query(), pixmapRect.size(), TomahawkUtils::ScaledCover, false ) ) );
            _detail::Closure* closure = NewClosure( m_pixmaps[ index ], SIGNAL( repaintRequest() ), const_cast<PlaylistChartItemDelegate*>(this), SLOT( doUpdateIndex( const QPersistentModelIndex& ) ), QPersistentModelIndex( index ) );
            closure->setAutoDelete( false );
        }

        const QPixmap pixmap = m_pixmaps[ index ]->currentPixmap();
        painter->drawPixmap( pixmapRect, pixmap );

        r.adjust( pixmapRect.width() + figureRect.width() + 18, 1, -28, 0 );
        QRect leftRect = r.adjusted( 0, 0, -48, 0 );
        QRect rightRect = r.adjusted( r.width() - 40, 0, 0, 0 );

        painter->setFont( boldFont );
        QString text = painter->fontMetrics().elidedText( track, Qt::ElideRight, leftRect.width() );
        painter->drawText( leftRect, text, m_topOption );

        painter->setFont( smallBoldFont );
        text = painter->fontMetrics().elidedText( artist, Qt::ElideRight, leftRect.width() );
        painter->drawText( index.row() >= 10 ? leftRect : leftRect.adjusted( 0, painter->fontMetrics().height() + 6, 0, 0 ), text, index.row() >= 10 ? m_bottomOption : m_topOption );

        if ( duration > 0 )
        {
            painter->setFont( durationFont );
            text = painter->fontMetrics().elidedText( TomahawkUtils::timeToString( duration ), Qt::ElideRight, rightRect.width() );
            painter->drawText( rightRect, text, m_centerRightOption );
        }
    }
void RangeLevelEditor::paintEvent(QPaintEvent *e) {

	if (!scale_1 || !scale_2 || !range_1 || !range_2)
		return;

	QPainter p(this);
	p.drawPixmap(0,0,skin.bg);
	p.setPen(skin.line_color);
	p.setClipRect(QRect(skin.border_w,skin.border_w,width()-skin.border_w*2,height()-skin.border_w*2));
	
	for (int i=0;i<width();i++) {
	
		float from_x=(float)i/(float)width();
		if (from_x<range_1->get())
			continue;
		if (from_x>range_2->get())
			break;
		
		float x=from_x-range_1->get();
		
		float y;
		if (range_1->get()==range_2->get())
			y=scale_1->get();
		else
			y=scale_1->get() + x * ( scale_2->get()-scale_1->get() ) / (range_2->get()-range_1->get());
		
		int h=(int)(y*height());
	
		QColor col_from=skin.line_color;
		col_from.setAlpha(40);
		QColor col_to=skin.line_color;
		col_to.setAlpha(200);
	
		QLinearGradient gradient(i, height(), i, height()-h);
		gradient.setColorAt(0,col_from);
		gradient.setColorAt(1, col_to);
		p.setBrush(gradient);
		p.fillRect(i, height()-h,1,h,gradient);
	} 
	
	p.drawPixmap(range_1->get()*width()-skin.point_from.width()/2,height()-scale_1->get()*height()-skin.point_from.height()/2,skin.point_from);
	p.drawPixmap(range_2->get()*width()-skin.point_to.width()/2,height()-scale_2->get()*height()-skin.point_to.height()/2,skin.point_to);
	
	/* DRAG TEXT */
	if (!click.drag_point)
		return;
	char buf[20]; //sprintf is still the best :(
	bool at_left;
	bool at_top;
	if (click.drag_point==1) {
		
		sprintf(buf,"%.2f,%.2f",(float)range_1->get(),(float)scale_1->get());
		at_left=range_1->get()>0.5;
		at_top=scale_1->get()<0.5;
	} else {
		
		sprintf(buf,"%.2f,%.2f",(float)range_2->get(),(float)scale_2->get());
		at_left=range_2->get()>0.5;
		at_top=scale_2->get()<0.5;
	}
	
	QString str=buf;
	QFont font;
	font.setPixelSize(10);
	p.setFont(font);
	QFontMetrics fm(p.font());
	
	int txt_x=at_left?3:width()-(fm.width(str)+3);
	int txt_y=at_top?(fm.ascent()+3):(height()-(fm.descent()+3));
	
	p.setPen( QColor(0,0,0) );
	p.drawText(txt_x-1,txt_y-1,str);
	p.drawText(txt_x-1,txt_y+1,str);
	p.drawText(txt_x+1,txt_y-1,str);
	p.drawText(txt_x+1,txt_y+1,str);
	p.setPen( QColor(255,255,255) );
	p.drawText(txt_x,txt_y,str);
	
	
	
	
	
}
Exemplo n.º 12
0
void EPGItem::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
    QPen pen;
    QColor gradientColor;

    // Draw in view's coordinates
    painter->setWorldMatrixEnabled( false );

    // Draw high-quality items
    //painter->setRenderHint( QPainter::Antialiasing );

    // Get the transformations required to map the text on the viewport
    QTransform viewPortTransform = m_view->viewportTransform();
    QRectF mapped = deviceTransform( viewPortTransform ).mapRect( boundingRect() );

    QLinearGradient gradient( mapped.topLeft(), mapped.bottomLeft() );

    bool b_simultaneous = playsAt( m_view->baseTime() );
    if ( m_current || b_simultaneous )
        gradientColor.setRgb( 244, 125, 0 , b_simultaneous ? 192 : 255 );
    else
        gradientColor.setRgb( 201, 217, 242 );

    gradient.setColorAt( 0.0, gradientColor.lighter( 120 ) );
    gradient.setColorAt( 1.0, gradientColor );

    pen.setColor( option->state & QStyle::State_MouseOver || hasFocus()
                  ? QColor( 0, 0, 0 ) : QColor( 192, 192, 192 ) );

    pen.setStyle( option->state & QStyle::State_MouseOver && !hasFocus()
                  ? Qt::DashLine : Qt::SolidLine );

    painter->setBrush( QBrush( gradient ) );
    painter->setPen( pen );
    mapped.adjust( 1, 2, -1, -2 );
    painter->drawRoundedRect( mapped, 10, 10 );

    /* Draw text */

    // Setup the font
    QFont f = painter->font();

    // Get the font metrics
    QFontMetrics fm = painter->fontMetrics();

    // Adjust the drawing rect
    mapped.adjust( 6, 6, -6, -6 );

    painter->setPen( Qt::black );
    /* Draw the title. */
    painter->drawText( mapped, Qt::AlignTop | Qt::AlignLeft, fm.elidedText( m_name, Qt::ElideRight, mapped.width() ) );

    mapped.adjust( 0, 20, 0, 0 );

    QDateTime m_end = m_start.addSecs( m_duration );
    f.setPixelSize( 10 );
    f.setItalic( true );
    painter->setFont( f );

    /* Draw the hours. */
    painter->drawText( mapped, Qt::AlignTop | Qt::AlignLeft,
                       fm.elidedText( start().toString( "hh:mm" ) + " - " +
                                      m_end.toString( "hh:mm" ),
                                      Qt::ElideRight, mapped.width() ) );
}
Exemplo n.º 13
0
//-----------------------------------------------------------------------------
//! Remote Upgrade Dialog
//-----------------------------------------------------------------------------
tOP40ConfigurationDialog::tOP40ConfigurationDialog(QWidget *pParent) 
    : tDialog( tDialog::Full, pParent )
    , m_pStackedLayout(0)
    , m_pSelWidget()
    , m_pSelLabel()
    , m_pFooterLabel(0)
    , m_pAssignAct(0)
    , m_pUnassignAct(0)
    , m_pNDP2kClient(0)
    , m_LastMfdControlledName()
    , m_pIncorrectOP40Timer(0)
    , m_pContextMenu(0)
{

    QString title = tr("%1 Configuration").arg(tUiConfig::Instance()->RemoteKeyboardDeviceName());
    setWindowTitle( title );

    m_pNDP2kClient = tNDP2kRemoteControlClient::Instance();
    int size = style()->pixelMetric( NPM( tNOSStyle::NPM_FontSizeLarge ), 0, this );
    QFont largeFont = font();
    largeFont.setPixelSize( size * 2 );

    // Main layout
    QLabel* pInstrLabel1 = new QLabel("Select number to assign this display to");
    QLabel* pOP40Image = new QLabel("");
    tProductSettings::Brand brand = tProductSettings::Instance().GetBrand();
    
    QString resourceFileName;
    if(brand == tProductSettings::BandG)
    {
        resourceFileName = tPath::ResourceFile( QString("bandg/ZC1_1234") );
    }
    else// if (brand == Simrad)
    {
        resourceFileName = tPath::ResourceFile( QString("simrad/OP40_1234") );
    }
    QPixmap op40Pixmap(resourceFileName);
    pOP40Image->setPixmap( op40Pixmap.scaledToWidth( 400 ) );
    QList<tNumSelectWidget*> numSelectWidgets;
    for( int i = 0; i < 4; ++i )
    {
        m_pSelWidget[i] = new tNumSelectWidget();
        m_pSelWidget[i]->setFocusPolicy( Qt::StrongFocus );
        numSelectWidgets << m_pSelWidget[i];
        m_pSelLabel[i] = new QLabel("");
        m_pSelLabel[i]->setFont( largeFont );
    }
    for( int i = 0; i < 4; ++i )
    {
        m_pSelWidget[i]->m_NumSelectWidgets = numSelectWidgets;
        m_pSelWidget[i]->m_pNDP2kClient = m_pNDP2kClient;
    }

    // 0 1 2 3 4 5 6 7 8 9 10 11
    // b |<-   OP40 imge  ->| b
    // b b 1 1 2 2 3 3 4 4 b  b
    QGridLayout* pWidgetLayout1 = new QGridLayout();
    // blank row 0
    pWidgetLayout1->addWidget( pInstrLabel1, 1, 0, 1, 12, Qt::AlignCenter );
    // blank row 2
    pWidgetLayout1->addWidget( pOP40Image, 3, 1, 1, 10, Qt::AlignCenter );
    pWidgetLayout1->addWidget( m_pSelWidget[0], 3, 2, 2, 2 );
    pWidgetLayout1->addWidget( m_pSelWidget[1], 3, 4, 2, 2 );
    pWidgetLayout1->addWidget( m_pSelWidget[2], 3, 6, 2, 2 );
    pWidgetLayout1->addWidget( m_pSelWidget[3], 3, 8, 2, 2 );
    pWidgetLayout1->addWidget( m_pSelLabel[0], 4, 2, 1, 2, Qt::AlignCenter );
    pWidgetLayout1->addWidget( m_pSelLabel[1], 4, 4, 1, 2, Qt::AlignCenter );
    pWidgetLayout1->addWidget( m_pSelLabel[2], 4, 6, 1, 2, Qt::AlignCenter );
    pWidgetLayout1->addWidget( m_pSelLabel[3], 4, 8, 1, 2, Qt::AlignCenter );
    // blank row 5
    pWidgetLayout1->setColumnStretch( 0, 1 );
    pWidgetLayout1->setColumnStretch( 11, 1 );
    pWidgetLayout1->setRowStretch( 0, 1 );
    pWidgetLayout1->setRowStretch( 2, 1 );
    pWidgetLayout1->setRowStretch( 4, 1 );
    pWidgetLayout1->setRowStretch( 5, 1 );

    QWidget* pWidget1 = new QWidget();
    pWidget1->setLayout( pWidgetLayout1 );
    pWidget1->setBackgroundRole(QPalette::Base);

    // Uncontrolled display layout
    QLabel* pInstrLabel2 = new QLabel( tr("Repeat press %1 to control this display")
        .arg(BUTTON_HTML(tNOSStyle::FP_ButtonImageDISP, "DISP")) );
    QGridLayout* pWidgetLayout2 = new QGridLayout();
    pWidgetLayout2->addWidget( pInstrLabel2, 0, 0, Qt::AlignCenter );
    QWidget widget2;
    QWidget* pWidget2 = new QWidget();
    pWidget2->setLayout( pWidgetLayout2 );

    // Incorrect OP40 pressed
    QLabel* pInstrLabel3a = new QLabel( tr("This %1 is not in configuration mode").arg(tUiConfig::Instance()->RemoteKeyboardDeviceName()) );
    QLabel* pInstrLabel3b = new QLabel( tr("Press and hold %1 to configure this %2")
        .arg(BUTTON_HTML(tNOSStyle::FP_ButtonImageDISP, "DISP")).arg(tUiConfig::Instance()->RemoteKeyboardDeviceName()) );
    QGridLayout* pWidgetLayout3 = new QGridLayout();
    pWidgetLayout3->setRowStretch( 0, 1 );
    pWidgetLayout3->addWidget( pInstrLabel3a, 1, 0, Qt::AlignCenter );
    pWidgetLayout3->addWidget( pInstrLabel3b, 2, 0, Qt::AlignCenter );
    pWidgetLayout3->setRowStretch( 3, 1 );
    QWidget widget3;
    QWidget* pWidget3 = new QWidget();
    pWidget3->setLayout( pWidgetLayout3 );

    // Layout stack
    m_pStackedLayout = new QStackedLayout();
    m_pStackedLayout->addWidget( pWidget1 );
    m_pStackedLayout->addWidget( pWidget2 );
    m_pStackedLayout->addWidget( pWidget3 );
    QWidget* pStackedWidget = new QWidget();
    pStackedWidget->setLayout( m_pStackedLayout );

    // Seperator
    QFrame* pSeparator = new QFrame();
    pSeparator->setFrameStyle( QFrame::HLine | QFrame::Plain );
    pSeparator->setLineWidth( 2 );

    // Footer
    m_pFooterLabel = new QLabel("");
    m_pFooterLabel->setFont( largeFont );

    UpdateDisplayFriendlyNameLabels();


    // Create main layout for page
    QVBoxLayout* pMainLayout = new QVBoxLayout();
    pMainLayout->addWidget(pStackedWidget, 1);
    pMainLayout->addWidget(pSeparator); //, 1, Qt::AlignCenter);
    pMainLayout->addWidget(m_pFooterLabel, 0, Qt::AlignCenter);
    setLayout(pMainLayout);

    m_pSelWidget[0]->setFocus();

    // if we have a SKB keys don't have focus, else hide keys
    if( HasSoftKeyBar() )
    {
        SoftKeyBar()->SetSoftKeyFocusPolicy( Qt::NoFocus );
    }
    else
    {
        SoftKeyBar()->ExplicitHide();
    }
    CreateActions();

    // Register types used in signals with Qt
    qRegisterMetaType<tRCDevice>("tRCDevice");

    Connect( m_pNDP2kClient, SIGNAL( RCDeviceUpdated(tRCDevice) ),
             this, SLOT( OnRCDeviceUpdated(tRCDevice) ) );

    Connect( m_pNDP2kClient, SIGNAL( GlobalAssignmentFinished() ),
             this, SLOT( accept() ) );

    Connect( m_pNDP2kClient, SIGNAL(IncorrectOP40used(bool)),
        this, SLOT(OnIncorrectOP40used(bool)) );
    m_pIncorrectOP40Timer = new QTimer( this );
    m_pIncorrectOP40Timer->setSingleShot( true );
    m_pIncorrectOP40Timer->setInterval( 2000 );
    Connect( m_pIncorrectOP40Timer, SIGNAL(timeout()), 
        this, SLOT(OnIncorrectOP40Timer()) );


    Connect( m_pNDP2kClient, SIGNAL(GlobalAssignmentOP40BeingConfiguredChanged( const tN2kName& )),
        this, SLOT(OnOP40BeingConfiguredChanged( const tN2kName& )) );

    m_pContextMenu = 0;
}
Exemplo n.º 14
0
void ImagePane::paintEvent(QPaintEvent* /*event*/)
{
    QPainter painter(this);

    //draw the transformed version of the text-object image
    painter.drawImage(0, 0, transformedImage);

    //then we draw the bounding boxes
    //TODO inscriptions with at least one graph are a different color (?)

    //in case index numbers are visible, set font
    QFont font;
    font.setPixelSize(30/zoom); //TODO make font size dependent on resolution
    painter.setFont(font);
    QPen pen;
    pen.setWidth(0);
    pen.setColor(Qt::red);
    painter.setPen(pen);
    //make a list of bounding boxes according to current mode
    BoxList currentBoxList; //this is a list of all boxes
    currentBoxList.clear();
    switch(mode)
    {
    case SURFACE:
        currentBoxList.append(*surf); //list of one item, consting of the surface bounding box
        break;
    case INSCRIPTION:
        for(int i=0; i < surf->inscriptionCount(); i++)
            currentBoxList.insertBox(surf->inscrAt(i), i);
        break;
    case GRAPH:
        for(int i=0; i < surf->ptrInscrAt(currentInscrIndex)->count(); i++)
            currentBoxList.insertBox(surf->ptrInscrAt(currentInscrIndex)->at(i), i);
        break;
    default:
       break;
    }
    //iterate through the list of bounding boxes
    for (int i=0; i<currentBoxList.size(); i++)
    {
        BoundingBox currentBox = currentBoxList.at(i);

        //the bounding boxes need to be rotated and scaled
        QTransform boxTransform; //identity matrix
        //first we need to handle the bounding box's own rotation
        //by inverting the true matrix that was applied to the image
        //at the time each bounding box was created
        //(note: we don't need to worry about scale, as we took account of that
        //when the bounding box was created)
        boxTransform.rotate(currentBox.getRotation());
        boxTransform = QImage::trueMatrix(boxTransform,
                                          currentImage.width(), currentImage.height());
        boxTransform = boxTransform.inverted();
	
        //then we compound the above matrix with the current transformation of the image
        QTransform imageTrueTransform = QImage::trueMatrix(transform,
                                                           currentImage.width(), currentImage.height());
        painter.setWorldTransform(boxTransform * imageTrueTransform);
        //now draw the box
        //pen color is red; set the pen-color to green if this is the current box.
        if(i==currentBoxIndex)
        {
            QPen pen;
            pen.setWidth(0);
            pen.setColor(Qt::green);
            painter.setPen(pen);
        }
        painter.drawRect(currentBox);
        //and add an (optional) index number
        if(indexNumbersVisible)
        {
            painter.drawText(currentBox.left(), currentBox.top(), 50/zoom, 50/zoom,
                             Qt::AlignBottom,  QString("%1").arg(i+1)); //visible index, so base = 1, not zero
        }
        //return pen color to red (might be green)
        QPen pen;
        pen.setWidth(0);
        pen.setColor(Qt::red);
        painter.setPen(Qt::red);
    }

    //if label is not resized, it will stay large on zoom out
    //resulting in misleading / redundant scroll bars
    resize(transformedImage.size()); // keep label same size as image
}
Exemplo n.º 15
0
LessonWindow::LessonWindow(QVector<Lesson *> lessons, QMdiArea *workspace) :
    QMainWindow(workspace)
{
    this->workspace = workspace;
    this->lessons = lessons;

    QWidget *central = new QWidget(this);
    setCentralWidget(central);

    this->setWindowTitle("Lessons");

    QHBoxLayout *horizontalContainer = new QHBoxLayout(central);

    tblLessons = new QTableWidget(central);
    tblLessons->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    tblLessons->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tblLessons->setSelectionMode(QAbstractItemView::SingleSelection);
    tblLessons->setSelectionBehavior(QAbstractItemView::SelectRows);
    tblLessons->setSortingEnabled(false);
    tblLessons->horizontalHeader()->setStretchLastSection(true);
    tblLessons->verticalHeader()->setVisible(false);
    tblLessons->horizontalHeader()->setVisible(false);
    tblLessons->setRowCount(lessons.size());
    tblLessons->setColumnCount(1);
    tblLessons->setMinimumSize(200, 300);
    QFont tblFont = tblLessons->font();
    tblFont.setPixelSize(12);
    tblLessons->setFont(tblFont);
    horizontalContainer->addWidget(tblLessons);

    for (int i = 0; i < lessons.size(); i++)
    {
        Lesson *lesson = lessons.at(i);
        tblLessons->setItem(i, 0, new QTableWidgetItem("Lesson " + QString::number(i+1) + ": " + lesson->getTitle()));
    }

    connect(tblLessons, SIGNAL(cellClicked(int,int)), this, SLOT(cellSelected(int,int)));
    connect(tblLessons, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(loadSelectedLesson()));

    QVBoxLayout *verticalContainer = new QVBoxLayout();
    horizontalContainer->addLayout(verticalContainer);

    lblPreviewImage = new QLabel(central);
    lblPreviewImage->setMinimumSize(300, 300);
    lblPreviewImage->setStyleSheet("background-color: #CCC");
    QImage image(":/resources/welcome.png");
    lblPreviewImage->setPixmap(QPixmap::fromImage(image));
    verticalContainer->addWidget(lblPreviewImage);

    lblDescription = new QLabel(central);
    lblDescription->setText("<b>Welcome</b><br/>Please select a lesson.");
    lblDescription->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    lblDescription->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
    lblDescription->setWordWrap(true);
    QFont lblFont = lblDescription->font();
    lblFont.setPixelSize(14);
    lblDescription->setFont(lblFont);
    verticalContainer->addWidget(lblDescription);

    QHBoxLayout *buttonContainer = new QHBoxLayout();
    verticalContainer->addLayout(buttonContainer);

    QPushButton *btnGo = new QPushButton("Go", central);
    connect(btnGo, SIGNAL(clicked()), this, SLOT(loadSelectedLesson()));
    buttonContainer->addWidget(btnGo);

    QPushButton *btnQuit = new QPushButton("Quit", central);
    connect(btnQuit, SIGNAL(clicked()), workspace->parentWidget()->parentWidget(), SLOT(close()));
    buttonContainer->addWidget(btnQuit);
}
Exemplo n.º 16
0
QFont Template::makeFont( const QFont & original,
        const QString & /* text */ /* = "MMMMMMMMMM" */ ) const
{
    Q_ASSERT( d != NULL );

    QFont result = original;

    int original_size = original.pixelSize();
    if( original_size == -1 ) original_size = original.pointSize();

    // compute scaling coeficient
    double scale =
        (this->rect().height() / (float)virtualRect().height());

#if BROKEN_ALGORITHM
    // compute width of dummy text for original font
    int original_w = QFontMetrics( original ).width( text );

    // compute fitting coeficient
    double original_fit = (float)original_w / (float)original_size;
#endif

    // compute proposed new size.
    int result_size = (int)(original_size * scale + 0.5);

    // stick to minimum font size 2 (to have space for decreasing)
    if( result_size < 2 ) result_size = 2;

    if( original.pixelSize() == -1 ) {
        result.setPointSize( result_size );
    } else {
        result.setPixelSize( result_size );
    }

#if BROKEN_ALGORITHM
    // compute width of dummy text for new font
    int result_w = QFontMetrics( result ).width( text );

    // compute fitting coeficient
    double result_fit = (float)result_w / (float)result_size;

    // if the new text will be logically wider, try to make the font smaller
    if( result_fit >= original_fit ) {
        qWarning( "Template::makeFont: need to decrease font by one" );
        if( original.pixelSize() == -1 ) {
            result.setPointSize( result_size - 1 );
        } else {
            result.setPixelSize( result_size - 1 );
        }
    }

    qWarning(
            "height %d -> height %d, scale = %f\n"
            "original_size = %d, original_twidth = %d, original_fit=%f\n"
            "result_size = %d, result_twidth = %d, result_fit=%f\n",
            virtualRect().height(), rect().height(), scale,
            original_size, original_w, original_fit,
            result_size, result_w, result_fit );
#endif

    return result;
}
Exemplo n.º 17
0
LifeWidget::LifeWidget(QWidget *parent, int nbCases)
    : QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
{
	assert(nbCases);
	
	showGrid = true;
	
	refreshTimer.setSingleShot(false);
    connect(&refreshTimer, SIGNAL(timeout()), this, SLOT(update()));
    refreshTimer.start(15);

    setAttribute(Qt::WA_NoSystemBackground);
    setMinimumSize(320, 320);
    setWindowTitle("LifeGame");
	
	mouseX = 0.0;
	mouseY = 0.0;
	
	posX = 0;
	posY = 0;
	
	setMouseTracking(true);
	
	this->nbCases = nbCases;
	lifeGame = new LifeGame(this->nbCases);
	
	toggleFullScreenAction = new QAction(this);
	toggleFullScreenAction->setShortcutContext(Qt::ApplicationShortcut);
	toggleFullScreenAction->setCheckable(true);
	toggleFullScreenAction->setShortcut(Qt::Key_Return | Qt::AltModifier);
	connect(toggleFullScreenAction, SIGNAL(triggered(bool)),
			this, SLOT(toggleFullScreen(bool)));
	
	toggleGridAction = new QAction(this);
	toggleGridAction->setShortcutContext(Qt::ApplicationShortcut);
	toggleGridAction->setCheckable(true);
	toggleGridAction->setShortcut(Qt::Key_G | Qt::AltModifier);
	connect(toggleGridAction, SIGNAL(triggered(bool)),
			this, SLOT(toggleGrid(bool)));
	
	nextGenerationAction = new QAction(this);
	nextGenerationAction->setShortcutContext(Qt::ApplicationShortcut);
	nextGenerationAction->setShortcut(Qt::Key_Plus);
	connect(nextGenerationAction, SIGNAL(triggered()),
			this, SLOT(computeNextGeneration()));
	
	clearGameAction = new QAction(this);
	clearGameAction->setShortcutContext(Qt::ApplicationShortcut);
	clearGameAction->setShortcut(Qt::Key_Asterisk);
	connect(clearGameAction, SIGNAL(triggered()),
			this, SLOT(clearGameTable()));
	
	addAction(toggleFullScreenAction);
	addAction(toggleGridAction);
	addAction(nextGenerationAction);
	addAction(clearGameAction);
	
	gameHud = new QtHud(this);
	QFont font;
	font.setFamily("Lucida Console");
	font.setPixelSize(14);
	font.setBold(true);
	gameHud->setFont(font);
	gameHud->setForeColor(QColor::fromRgb(0, 255, 127));
}
Exemplo n.º 18
0
GroupChatForm::GroupChatForm(Group* chatGroup)
    : group(chatGroup), curRow{0}, lockSliderToBottom{true}
{
    main = new QWidget(), head = new QWidget(), chatAreaWidget = new QWidget();
    headLayout = new QHBoxLayout(), mainFootLayout = new QHBoxLayout();
    headTextLayout = new QVBoxLayout(), mainLayout = new QVBoxLayout();
    mainChatLayout = new QGridLayout();
    avatar = new QLabel(), name = new QLabel(), nusers = new QLabel(), namesList = new QLabel();
    msgEdit = new ChatTextEdit();
    sendButton = new QPushButton();
    chatArea = new QScrollArea();
    QFont bold;
    bold.setBold(true);
    QFont small;
    small.setPixelSize(10);
    name->setText(group->widget->name.text());
    name->setFont(bold);
    nusers->setFont(small);
    nusers->setText(GroupChatForm::tr("%1 users in chat","Number of users in chat").arg(group->peers.size()));
    avatar->setPixmap(QPixmap(":/img/group.png"));
    QString names;
    for (QString& s : group->peers)
        names.append(s+", ");
    names.chop(2);
    namesList->setText(names);
    namesList->setFont(small);

    chatAreaWidget->setLayout(mainChatLayout);

    chatArea->setStyleSheet(Style::get(":/ui/chatArea/chatArea.css"));
    chatArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    chatArea->setWidgetResizable(true);
    chatArea->setContextMenuPolicy(Qt::CustomContextMenu);
    chatArea->setFrameStyle(QFrame::NoFrame);

    mainChatLayout->setColumnStretch(1,1);
    mainChatLayout->setSpacing(10);

    msgEdit->setObjectName("group");
    msgEdit->setStyleSheet(Style::get(":/ui/msgEdit/msgEdit.css"));
    msgEdit->setFixedHeight(50);
    msgEdit->setFrameStyle(QFrame::NoFrame);

    mainChatLayout->setColumnStretch(1,1);
    mainChatLayout->setHorizontalSpacing(10);

    sendButton->setStyleSheet(Style::get(":/ui/sendButton/sendButton.css"));
    sendButton->setFixedSize(50, 50);

    main->setLayout(mainLayout);
    mainLayout->addWidget(chatArea);
    mainLayout->addLayout(mainFootLayout);
    mainLayout->setMargin(0);

    mainFootLayout->addWidget(msgEdit);
    mainFootLayout->addWidget(sendButton);

    head->setLayout(headLayout);
    headLayout->addWidget(avatar);
    headLayout->addLayout(headTextLayout);
    headLayout->addStretch();
    headLayout->setMargin(0);

    headTextLayout->addStretch();
    headTextLayout->addWidget(name);
    headTextLayout->addWidget(nusers);
    headTextLayout->addWidget(namesList);
    headTextLayout->setMargin(0);
    headTextLayout->setSpacing(0);
    headTextLayout->addStretch();

    chatArea->setWidget(chatAreaWidget);

    sendButton->setAttribute(Qt::WA_LayoutUsesWidgetRect);

    connect(sendButton, SIGNAL(clicked()), this, SLOT(onSendTriggered()));
    connect(msgEdit, SIGNAL(enterPressed()), this, SLOT(onSendTriggered()));
    connect(chatArea->verticalScrollBar(), SIGNAL(rangeChanged(int,int)), this, SLOT(onSliderRangeChanged()));
    connect(chatArea, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onChatContextMenuRequested(QPoint)));
}
Exemplo n.º 19
0
void QScreenDistribution::paintEvent(QPaintEvent *event)
{
    m_screens.clear();

    // Calcul de les posicions on s'haurà de pintar les diferents icones de finestres.
    computeSizesAndPositions();

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QPen pen = QPen(Qt::white, 2, Qt::SolidLine);
    painter.setPen(pen);

    QFont font;
    font.setPixelSize(m_screenNumberPixelSize);
    painter.setFont(font);

    for (int i = 0; i < m_screens.count(); i++)
    {
        if (m_mouseInScreen == i)
        {
            QLinearGradient linearGradient(0.1, 0.1, 1.2, 1.2);
            linearGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
            linearGradient.setColorAt(0, QColor("#777777"));
            linearGradient.setColorAt(1, QColor("#111111"));
            painter.setBrush(QBrush(linearGradient));
            painter.drawRoundedRect(m_screens.at(i), 2, 2);

            QRadialGradient radialGradient(0.9, 2.1, 2.5);
            radialGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
            radialGradient.setColorAt(0, QColor(255, 255, 255, 0));
            radialGradient.setColorAt(0.74, QColor(255, 255, 255, 0));
            radialGradient.setColorAt(0.75, QColor(255, 255, 255, 40));
            radialGradient.setColorAt(1, QColor(255, 255, 255, 0));
            painter.setBrush(QBrush(radialGradient));
            painter.drawRoundedRect(m_screens.at(i), 2, 2);
        }
        else
        {
            painter.setPen(Qt::NoPen);

            QLinearGradient linearGradient(0.1, 0.1, 1.2, 1.2);
            linearGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
            linearGradient.setColorAt(0, QColor("#666666"));
            linearGradient.setColorAt(1, QColor("#000000"));
            painter.setBrush(QBrush(linearGradient));
            painter.drawRoundedRect(m_screens.at(i), 2, 2);

            QRadialGradient radialGradient(0.9, 2.1, 2.5);
            radialGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
            radialGradient.setColorAt(0, QColor(255, 255, 255, 0));
            radialGradient.setColorAt(0.74, QColor(255, 255, 255, 0));
            radialGradient.setColorAt(0.75, QColor(255, 255, 255, 40));
            radialGradient.setColorAt(1, QColor(255, 255, 255, 0));
            painter.setBrush(QBrush(radialGradient));
            painter.drawRoundedRect(m_screens.at(i), 2, 2);

            painter.setPen(pen);
        }

        // Pintar el numero
        painter.drawText(m_screens.at(i), Qt::AlignCenter, QString::number(i + 1));
    }
    event->accept();
}
Exemplo n.º 20
0
PrintSheet::PrintSheet( DigiDoc *doc, QPrinter *printer )
:	QPainter( printer )
,	p( printer )
{
	printer->setOrientation( QPrinter::Portrait );

	int left	= p->pageRect().x();
	int margin	= left;
	int right	= p->pageRect().topRight().x() - 2*margin;
	top			= p->pageRect().topLeft().y() + 30;

#ifdef Q_OS_MAC
	scale( 0.8, 0.8 );
	right /= 0.8;
#endif

	QFont text = font();
	text.setFamily( "Arial, Helvetica, sans-serif" );
	text.setPixelSize( 12 );

	QFont head = text;
	head.setPixelSize( 28 );

	QFont sHead = head;
	sHead.setPixelSize( 18 );

	QPen oPen = pen();

	QPen hPen = oPen;
	hPen.setWidth( 2 );

	QPen sPen = oPen;
	sPen.setWidth( 1 );
	sPen.setStyle( Qt::DotLine );

	setFont( head );
	drawText( left, top, tr("VALIDITY CONFIRMATION SHEET") );
	setPen( hPen );
	drawLine( left, top+3, right, top+3 );
	top += 45;

	setFont( sHead );
	drawText( left, top, tr("SIGNED FILES") );
	setPen( sPen );
	drawLine( left, top+3, right, top+3 );
	top += 30;
	
	setFont( text );
	setPen( oPen );
	drawText( left, top, tr("FILE NAME") );
	drawText( left+400, top, tr("FILE SIZE") );
	drawRect( left, top+5, right - margin, 20*doc->documentModel()->rowCount() );
	for( int i = 0; i < doc->documentModel()->rowCount(); ++i )
	{
		drawLine( left+395, top+5, left+395, top+25 );
		top += 20;
		drawText( left+5, top, doc->documentModel()->index( i, 0 ).data().toString() );
		drawText( left+400, top, doc->documentModel()->index( i, 2 ).data().toString() );
		drawLine( left, top+5, right, top+5 );
	}
	top += 35;

	newPage( 50 );
	setFont( sHead );
	drawText( left, top, tr("SIGNERS") );
	setPen( sPen );
	drawLine( left, top+3, right, top+3 );
	top += 30;
	
	setFont( text );
	setPen( oPen );

	int i = 1;
	Q_FOREACH( const DigiDocSignature &sig, doc->signatures() )
	{
		newPage( 50 );
		const SslCertificate cert = sig.cert();
		bool tempel = cert.isTempel();

		drawText( left, top, tr("NO.") );
		drawLine( left+35, top+5, left+35, top+25 );
		drawText( left+40, top, tempel ? tr( "COMPANY" ) : tr( "NAME" ) );
		drawLine( right-285, top+5, right-285, top+25 );
		drawText( right-280, top, tempel ? tr("REGISTER CODE") : tr("PERSONAL CODE") );
		drawLine( right-145, top+5, right-145, top+25 );
		drawText( right-140, top, tr("TIME") );
		drawRect( left, top+5, right - margin, 20 );
		top += 20;

		drawText( left+5, top, QString::number( i ) );
		drawText( left+40, top, cert.toString( cert.showCN() ? "CN" : "GN SN" ) );
		drawText( right-280, top, cert.subjectInfo( "serialNumber" ) );
		drawText( right-140, top, sig.dateTime().toString( "dd.MM.yyyy hh:mm:ss" ) );
		top += 25;

		newPage( 50 );
		drawText( left+3, top, tr("VALIDITY OF SIGNATURE") );
		drawRect( left, top+5, right - margin, 20 );
		QString valid = tr("SIGNATURE")+" ";
		switch( sig.validate() )
		{
			case DigiDocSignature::Valid: valid.append( tr("VALID") ); break;
			case DigiDocSignature::Invalid: valid.append( tr("NOT VALID") ); break;
			case DigiDocSignature::Unknown: valid.append( tr("UNKNOWN") ); break;
		}
		if( sig.isTest() )
			valid += " " + tr("(NB! TEST SIGNATURE)");
		drawText( left+5, top+20, valid );
		top += 45;

		newPage( 50 );
		drawText( left+3, top, tr("ROLE / RESOLUTION") );
		drawRect( left, top+5, right - margin, 20 );
		drawText( left+5, top+20, sig.role() );
		top += 45;

		newPage( 50 );
		drawText( left+3, top, tr("PLACE OF CONFIRMATION (CITY, STATE, ZIP, COUNTRY)") );
		drawText( right-200, top, tr("SERIAL NUMBER OF CERTIFICATE") );
		drawRect( left, top+5, right - margin, 20 );
		drawLine( right-205, top+5, right-205, top+25 );
		drawText( left+5, top+20, sig.location() );
		drawText( right-200, top+20, cert.serialNumber() );
		top += 45;

		newPage( 50 );
		drawText( left+3, top, tr("ISSUER OF CERTIFICATE") );
		drawText( left+187, top, tr("HASH VALUE OF ISSUER'S PUBLIC KEY") );
		drawRect( left, top+5, right - margin, 20 );
		drawLine( left+180, top+5, left+180, top+25 );
		drawText( left+5, top+20, cert.issuerInfo( QSslCertificate::CommonName ) );
		drawText( left+187, top+20, cert.toHex( cert.authorityKeyIdentifier() ) );
		top += 45;

		newPage( 60 );
		drawText( left+3, top, tr("HASH VALUE OF VALIDITY CONFIRMATION (OCSP RESPONSE)") );
		drawRect( left, top+5, right - margin, 20 );
		drawText( left+5, top+20, cert.toHex( sig.digestValue() ) );
		top += 60;

		++i;
	}
	save();
	newPage( 50 );
	QTextDocument textDoc;
	textDoc.setTextWidth( right - margin );
	textDoc.setHtml( tr("The print out of files listed in the section <b>\"Signed Files\"</b> "
						"are inseparable part of this Validity Confirmation Sheet.") );
	translate( QPoint( left, top - 30) );
	textDoc.drawContents( this , QRectF( 0, 0, right - margin, 40) );
	top += 30;
	restore();

	newPage( 90 );
	drawText( left+3, top, tr("NOTES") );
	top += 10;
	drawRect( left, top, right - margin, 80 );

	end();
}
Exemplo n.º 21
0
QFont QgsMapToolLabel::labelFontCurrentFeature()
{
  QFont font;
  QgsVectorLayer* vlayer = currentLayer();

  bool labelSettingsOk;
  QgsPalLayerSettings& labelSettings = currentLabelSettings( &labelSettingsOk );

  if ( labelSettingsOk && vlayer )
  {
    font = labelSettings.textFont;

    QgsFeature f;
    if ( vlayer->getFeatures( QgsFeatureRequest().setFilterFid( mCurrentLabelPos.featureId ).setFlags( QgsFeatureRequest::NoGeometry ) ).nextFeature( f ) )
    {
      //size
      int sizeIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Size, vlayer );
      if ( sizeIndx != -1 )
      {
        if ( labelSettings.fontSizeInMapUnits )
        {
          font.setPixelSize( labelSettings.sizeToPixel( f.attribute( sizeIndx ).toDouble(),
                             QgsRenderContext(), QgsPalLayerSettings::MapUnits, true ) );
        }
        else
        {
          font.setPointSizeF( f.attribute( sizeIndx ).toDouble() );
        }
      }

      //family
      int fmIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Family, vlayer );
      if ( fmIndx != -1 )
      {
        font.setFamily( f.attribute( fmIndx ).toString() );
      }

      //underline
      int ulIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Underline, vlayer );
      if ( ulIndx != -1 )
      {
        font.setUnderline( f.attribute( ulIndx ).toBool() );
      }

      //strikeout
      int soIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Strikeout, vlayer );
      if ( soIndx != -1 )
      {
        font.setStrikeOut( f.attribute( soIndx ).toBool() );
      }

      //bold
      int boIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Bold, vlayer );
      if ( boIndx != -1 )
      {
        font.setBold( f.attribute( boIndx ).toBool() );
      }

      //italic
      int itIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Italic, vlayer );
      if ( itIndx != -1 )
      {
        font.setItalic( f.attribute( itIndx ).toBool() );
      }

      // TODO: Add other font data defined values (word spacing, etc.)
    }
  }

  return font;
}
//---------------------------------------------------------------------------
//  makePixmap
//
//! Create a pixmap representation of the rack.
//
//! @return the pixmap
//---------------------------------------------------------------------------
QPixmap
CrosswordGameRackWidget::makePixmap() const
{
    QPixmap pixmap (getRackSize());
    QPainter painter (&pixmap);

    // FIXME: most of this is duplicated between BoardWidget and here
    QColor backgroundColor = BACKGROUND_COLOR;
    QPalette backgroundPalette;
    backgroundPalette.setColor(QPalette::Light,
                               backgroundColor.light(SQUARE_SHADE_VALUE));
    backgroundPalette.setColor(QPalette::Mid, backgroundColor);
    backgroundPalette.setColor(QPalette::Dark,
                               backgroundColor.dark(SQUARE_SHADE_VALUE));

    for (int i = 0; i < NUM_TILES; ++i) {
        QRect rect (i * COLUMN_WIDTH, 0, COLUMN_WIDTH, ROW_HEIGHT);
        painter.setPen(backgroundColor);
        painter.setBrush(backgroundColor);
        painter.drawRect(rect);

        qDrawShadePanel(&painter, rect, backgroundPalette, false,
                        SQUARE_SHADE_PANEL_WIDTH);


        if (i >= letters.length())
            continue;

        QRect tileRect(i * COLUMN_WIDTH + TILE_MARGIN, TILE_MARGIN,
                       COLUMN_WIDTH - 2 * TILE_MARGIN -
                       SQUARE_SHADE_PANEL_WIDTH,
                       ROW_HEIGHT - 2 * TILE_MARGIN -
                       SQUARE_SHADE_PANEL_WIDTH);

        QColor color = TILE_COLOR;
        QPalette palette;
        palette.setColor(QPalette::Light,
                         color.light(TILE_SHADE_VALUE));
        palette.setColor(QPalette::Mid, color);
        palette.setColor(QPalette::Dark,
                         color.dark(TILE_SHADE_VALUE));

        painter.setPen(QColor("black"));
        painter.setBrush(color);
        painter.drawRect(tileRect);
        qDrawShadePanel(&painter, tileRect, palette, false,
                        TILE_SHADE_PANEL_WIDTH);

        QFont tileFont = font();
        tileFont.setPixelSize(LETTER_HEIGHT);
        tileFont.setWeight(QFont::Black);
        painter.setFont(tileFont);

        switch (playerNum) {
            case 1:  color = PLAYER1_LETTER_COLOR; break;
            case 2:  color = PLAYER2_LETTER_COLOR; break;
            default: color = DEFAULT_LETTER_COLOR; break;
        }
        painter.setPen(QPen(color));

        QChar letter = letters[i];
        if (letter == '?') {
            QPen pen (color);
            pen.setWidth(1);
            painter.setPen(pen);
            painter.setBrush(Qt::NoBrush);
            QRect blankRect(rect.x() + BLANK_SQUARE_MARGIN,
                            rect.y() + BLANK_SQUARE_MARGIN,
                            rect.width() - 2 * BLANK_SQUARE_MARGIN -
                            SQUARE_SHADE_PANEL_WIDTH - 1,
                            rect.height() - 2 * BLANK_SQUARE_MARGIN -
                            SQUARE_SHADE_PANEL_WIDTH - 1);
            painter.drawRect(blankRect);
        }

        else {
            painter.drawText(rect, Qt::AlignCenter, letter);
        }
    }

    return pixmap;
}
Exemplo n.º 23
0
SyntaxEditorWindow::SyntaxEditorWindow(const QSharedPointer<SyntaxList> &syntaxList, const QString &syntaxName,
		const QString &category, const QString &syntaxHint, QWidget *parent) :
		QWidget(parent), syntaxList(syntaxList), syntaxName(syntaxName)
{
	setWindowRole("kadu-syntax-editor");

	setWindowTitle(tr("Kadu syntax editor"));
	setAttribute(Qt::WA_DeleteOnClose);

	QVBoxLayout *layout = new QVBoxLayout(this);

	QSplitter *splitter = new QSplitter(this);
	layout->addWidget(splitter);
	splitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	splitter->setChildrenCollapsible(false);

	QWidget *splitterleft = new QWidget(splitter);
	QVBoxLayout *splitterleftlayout = new QVBoxLayout(splitterleft);
	splitterleftlayout->setMargin(0);
	splitterleftlayout->setSpacing(5);

	editor = new QTextEdit(this);
	splitterleftlayout->addWidget(editor);
	editor->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	editor->setAcceptRichText(true);
	editor->setPlainText(syntaxList->readSyntax(syntaxName));
	QFont font = this->font();
	font.setFamily("monospace");
	if(font.pixelSize() == -1)
		font.setPointSizeF(font.pointSizeF() - 0.5);
	else
		font.setPixelSize(font.pixelSize() - 2);
	editor->setFont(font);
	editor->setMinimumSize(EDITOR_MINIMUM_SIZE);

	if (!syntaxHint.isEmpty())
	{
		QLabel *editorhint = new QLabel(this);
		splitterleftlayout->addWidget(editorhint);
		editorhint->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
		editorhint->setWordWrap(true);
		editorhint->setText(syntaxHint);
	}

	QWidget *splitterright = new QWidget(splitter);
	QVBoxLayout *splitterrightlayout = new QVBoxLayout(splitterright);
	splitterrightlayout->setMargin(0);
	splitterrightlayout->setSpacing(5);

	previewPanel = new Preview(this);
	splitterrightlayout->addWidget(previewPanel);
	previewPanel->setMinimumHeight(0);
	previewPanel->setMaximumHeight(QWIDGETSIZE_MAX);
	previewPanel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
	previewPanel->setResetBackgroundColor(config_file.readEntry("Look", category + "BgColor"));
	previewPanel->setMinimumSize(PREVIEW_MINIMUM_SIZE);

	QPushButton *previewbutton = new QPushButton(qApp->style()->standardIcon(QStyle::SP_BrowserReload), tr("Refresh Preview"), this);
	splitterrightlayout->addWidget(previewbutton);
	connect(previewbutton, SIGNAL(clicked()), this, SLOT(refreshPreview()));

	QDialogButtonBox *buttonslayout = new QDialogButtonBox(Qt::Horizontal, this);
	layout->addWidget(buttonslayout);
	QPushButton *saveSyntax = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogOkButton), tr("Save"), this);
	QPushButton *saveAsSyntax = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogSaveButton), tr("Save as..."), this);
	QPushButton *cancel = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogCancelButton), tr("Cancel"), this);
	buttonslayout->addButton(saveSyntax, QDialogButtonBox::YesRole);
	buttonslayout->addButton(saveAsSyntax, QDialogButtonBox::ActionRole);
	buttonslayout->addButton(cancel, QDialogButtonBox::RejectRole);

	splitter->setSizes( QList<int>() << splitter->sizeHint().width() << 1 );

	if (syntaxList->isGlobal(syntaxName))
		saveSyntax->setDisabled(true);
	else
		connect(saveSyntax, SIGNAL(clicked()), this, SLOT(save()));
	connect(saveAsSyntax, SIGNAL(clicked()), this, SLOT(saveAs()));
	connect(cancel, SIGNAL(clicked()), this, SLOT(close()));

	loadWindowGeometry(this, "Look", "SyntaxEditorGeometry", 0, 50, 790, 480);
}
Exemplo n.º 24
0
void LightMaps::paintEvent(QPaintEvent *event)
{
    QPainter p;
    p.begin(this);
    m_normalMap->render(&p, event->rect());
    p.setPen(Qt::black);
#if defined(Q_OS_SYMBIAN)
    QFont font = p.font();
    font.setPixelSize(13);
    p.setFont(font);
#endif
    p.drawText(rect(),  Qt::AlignBottom | Qt::TextWordWrap,
                "Map data CCBYSA 2009 OpenStreetMap.org contributors");
    p.end();

    if (zoomed) {
        int dim = qMin(width(), height());
        int magnifierSize = qMin(MAX_MAGNIFIER, dim * 2 / 3);
        int radius = magnifierSize / 2;
        int ring = radius - 15;
        QSize box = QSize(magnifierSize, magnifierSize);

        // reupdate our mask
        if (maskPixmap.size() != box) {
            maskPixmap = QPixmap(box);
            maskPixmap.fill(Qt::transparent);

            QRadialGradient g;
            g.setCenter(radius, radius);
            g.setFocalPoint(radius, radius);
            g.setRadius(radius);
            g.setColorAt(1.0, QColor(255, 255, 255, 0));
            g.setColorAt(0.5, QColor(128, 128, 128, 255));

            QPainter mask(&maskPixmap);
            mask.setRenderHint(QPainter::Antialiasing);
            mask.setCompositionMode(QPainter::CompositionMode_Source);
            mask.setBrush(g);
            mask.setPen(Qt::NoPen);
            mask.drawRect(maskPixmap.rect());
            mask.setBrush(QColor(Qt::transparent));
            mask.drawEllipse(g.center(), ring, ring);
            mask.end();
        }

        QPoint center = dragPos - QPoint(0, radius);
        center = center + QPoint(0, radius / 2);
        QPoint corner = center - QPoint(radius, radius);

        QPoint xy = center * 2 - QPoint(radius, radius);

        // only set the dimension to the magnified portion
        if (zoomPixmap.size() != box) {
            zoomPixmap = QPixmap(box);
            zoomPixmap.fill(Qt::lightGray);
        }
        if (true) {
            QPainter p(&zoomPixmap);
            p.translate(-xy);
            m_largeMap->render(&p, QRect(xy, box));
            p.end();
        }

        QPainterPath clipPath;
        clipPath.addEllipse(center, ring, ring);

        QPainter p(this);
        p.setRenderHint(QPainter::Antialiasing);
        p.setClipPath(clipPath);
        p.drawPixmap(corner, zoomPixmap);
        p.setClipping(false);
        p.drawPixmap(corner, maskPixmap);
        p.setPen(Qt::gray);
        p.drawPath(clipPath);
    }
    if (invert) {
        QPainter p(this);
        p.setCompositionMode(QPainter::CompositionMode_Difference);
        p.fillRect(event->rect(), Qt::white);
        p.end();
    }
}
Exemplo n.º 25
0
void FilterBar::paintEvent(QPaintEvent *e){
    if (history.length()>0 && t==HISTORY){
        QPainter p(this);
        QColor fg(60,60,60);

        p.setRenderHint(p.Antialiasing);
        QFont f;
        f.setFamily("URW Gothic L");
//        f.setBold(true);
        f.setPixelSize(16);
        p.setFont(f);

        for (int i=0; i<history.length();i++){
            p.setPen(fg);

            if (index==i) {
                f.setBold(true);
                p.setFont(f);
                QFontMetrics fm(f);
                historyButton[i].setWidth(fm.width(history[i]));
            }
            else if (f.bold()) {
                f.setBold(false);
                p.setFont(f);

            }


            p.drawText(historyButton[i],Qt::AlignCenter,history[i]);
            if (i<history.length()-1) {
                QPen p1;

                p1.setColor(fg);
                p1.setWidth(3);
                p1.setCapStyle(Qt::RoundCap);

                p.setPen(p1);

                int xc,yc;
                xc=historyButton[i].x()+historyButton[i].width()+12;
                yc=height()/2-1;
                    
                p.drawLine(xc+2,yc+3,xc-1,yc);
                p.drawLine(xc+2,yc+3,xc-1,yc+6);
            }
        }

    }
    else {
        QPainter p(this);
        p.setRenderHint(p.Antialiasing);
        QFont f;
        f.setFamily("URW Gothic L");
//        f.setBold(true);
        f.setPixelSize(16);
        p.setFont(f);

        QColor fg(60,60,60);
        p.setPen(fg);
        QFontMetrics fm(f);
        int x=10;
        int y=height()/2-fm.height()/2;
        for (int i=0; i<filters.length();i++){
            QRect r(x,y,fm.width(filters[i]),fm.height());
            p.drawText(r,Qt::AlignCenter,filters[i]);
            if (i<filters.length()-1){
                p.save();
                p.translate(x+fm.width(filters[i])+19,height()/2+1);
                paintIntersection(p);
                p.restore();
            }
            x+=fm.width(filters[i])+40;
        }
    }
    e->accept();
}
Exemplo n.º 26
0
void
ProgressBar::paintEvent( QPaintEvent* e )
{
    QFrame::paintEvent( e );

    QPainter p( this );

    StopWatch* sw = ScrobbleService::instance().stopWatch();

    if ( m_track != Track() )
    {
        QFont timeFont = font();
        timeFont.setPixelSize( 10 );
        setFont( timeFont );

        p.setPen( QColor( 0x333333 ) );

        if ( m_track.extra( "playerId" ) != "spt" )
        {
            if ( m_track.duration() >= 30 )
            {
                QString format( "m:ss" );

                QTime duration( 0, 0 );
                duration = duration.addMSecs( m_track.duration() * 1000 );
                QTime progress( 0, 0 );
                progress = progress.addMSecs( m_frame );

                if ( duration.hour() > 0 )
                    format = "h:mm:ss";

                QTextOption timeTextOption;
                timeTextOption.setAlignment( Qt::AlignVCenter | Qt::AlignLeft );

                QString timeText;

                if ( m_track.source() == Track::LastFmRadio )
                    timeText = QString( "%1 / %2" ).arg( progress.toString( format ), duration.toString( format ) );
                else
                    timeText = QString( "%1" ).arg( progress.toString( format ) );

                p.setPen( QColor( 0x333333 ) );
                p.drawText( rect().adjusted( 6, 0, 0, 0 ), timeText, timeTextOption );

                QFontMetrics fm( font() );
                int indent = fm.width( timeText ) + ( 2 * 6 ) + 2;

                int width = this->width() - indent;

                p.setPen( QColor( 0xbdbdbd ));
                p.drawLine( QPoint( indent - 2, rect().top() ),
                            QPoint( indent - 2, rect().bottom() - 1 ) );

                p.setPen( QColor( 0xe6e6e6 ) );
                p.drawLine( QPoint( indent - 1, rect().top() ),
                            QPoint( indent - 1, rect().bottom() - 1 ) );


                // draw the chunk
                p.setPen( Qt::transparent );
                p.setBrush( m_chunk );
                p.drawRect( rect().adjusted( indent, 0, ((m_frame * width) / (m_track.duration() * 1000)) - width, -1) );

                //bool scrobblingOn = unicorn::UserSettings().value( "scrobblingOn", true ).toBool();
                bool scrobblingOn = ScrobbleService::instance().scrobblableTrack( m_track );

                if ( scrobblingOn ||
                     ( !scrobblingOn && (m_track.scrobbleStatus() != Track::Null) ) )
                {
                    if ( !scrobblingOn && m_track.scrobbleStatus() != Track::Null )
                    {
                        QTextOption textOption;
                        textOption.setAlignment( Qt::AlignVCenter | Qt::AlignRight );
                        p.drawText( rect().adjusted( 0, 0, -6, 0 ), tr( "Scrobbling off" ), textOption );
                    }

                    uint scrobblePoint = sw->scrobblePoint() * 1000;

                    int scrobbleMarker = indent + (scrobblePoint * width) / ( m_track.duration() * 1000 );

                    p.setPen( QPen( QColor( 0xbdbdbd ), 1, Qt::DashLine) );
                    p.drawLine( QPoint( scrobbleMarker - 1, rect().top() ),
                                QPoint( scrobbleMarker - 1, rect().bottom() ) );

                    p.setPen( QPen( QColor( 0xe6e6e6 ), 1, Qt::DashLine) );
                    p.drawLine( QPoint( scrobbleMarker, rect().top() ),
                                QPoint( scrobbleMarker, rect().bottom() ) );

                    // Draw the 'as'!
                    // if the scrobble marker is too close to the left draw the 'as' on the right hand side
                    QPoint asPoint;
                    QImage as( m_track.scrobbleStatus() != Track::Null ? m_scrobbleMarkerOn : m_scrobbleMarkerOff );

                    if ( ( as.width() + 10 ) > scrobbleMarker - indent )
                        asPoint = QPoint ( scrobbleMarker + 5 , (rect().height() / 2) - (as.height() / 2) );
                    else
                        asPoint = QPoint ( scrobbleMarker - as.width() - 5, (rect().height() / 2) - (as.height() / 2) );

                    p.drawImage( asPoint, as );

                }
                else
                {
                    QString offMessage = NULL;

                    if ( unicorn::UserSettings().value( "scrobblingOn", true ).toBool() )
                    {
                        if ( m_track.isVideo() )
                            offMessage = tr( "Not scrobbling - not a music video" );
                        else if ( !unicorn::UserSettings().value( "podcasts", true ).toBool() && m_track.isPodcast() )
                            offMessage = tr( "Not scrobbling - podcasts disabled" );
                        else if ( m_track.artist().isNull() )
                            offMessage = tr( "Not scrobbling - missing artist" );
                    }

                    if(offMessage != NULL)
                    {
                        p.setPen( QColor( 0x333333 ) );
                        QTextOption textOption;
                        textOption.setAlignment( Qt::AlignVCenter | Qt::AlignRight );
                        p.drawText( rect().adjusted( 0, 0, -6, 0 ), offMessage, textOption );
                    }
                }
            }
            else
            {
                QTextOption textOption;
                textOption.setAlignment( Qt::AlignVCenter | Qt::AlignRight );
                p.drawText( rect().adjusted( 0, 0, -6, 0 ), tr( "Not scrobbling - track too short" ), textOption );
            }
        }
        else
        {
            QTextOption textOption;
            textOption.setAlignment( Qt::AlignVCenter | Qt::AlignRight );
            p.drawText( rect().adjusted( 0, 0, -6, 0 ), tr("Enable scrobbling in Spotify's preferences!"), textOption );
        }
    }
}
Exemplo n.º 27
0
MainWindow::MainWindow()
    : m_currentView(0),
      m_currentRootObject(0),
      m_transparent(false)
{
    QVBoxLayout *layout = new QVBoxLayout;

    QGroupBox *groupBox = new QGroupBox(tr("Type"));
    QVBoxLayout *vbox = new QVBoxLayout;
    m_radioView = new QRadioButton(tr("QQuickView in a window container (direct)"));
    m_radioWidget = new QRadioButton(tr("QQuickWidget (indirect through framebuffer objects)"));
    vbox->addWidget(m_radioWidget);
    vbox->addWidget(m_radioView);
    m_radioWidget->setChecked(true);
    m_state = Unknown;
    connect(m_radioWidget, &QRadioButton::toggled, this, &MainWindow::updateView);
    connect(m_radioView, &QRadioButton::toggled, this, &MainWindow::updateView);
    groupBox->setLayout(vbox);

    layout->addWidget(groupBox);

    m_checkboxMultiSample = new QCheckBox(tr("Multisample (4x)"));
    connect(m_checkboxMultiSample, &QCheckBox::toggled, this, &MainWindow::updateView);
    layout->addWidget(m_checkboxMultiSample);

    m_labelStatus = new QLabel;
    layout->addWidget(m_labelStatus);

    qmlRegisterType<FbItem>("fbitem", 1, 0, "FbItem");

    QWidget *quickContainer = new QWidget;
    layout->addWidget(quickContainer);
    layout->setStretchFactor(quickContainer, 8);
    m_containerLayout = new QVBoxLayout;
    quickContainer->setLayout(m_containerLayout);

    // Add an overlay widget to demonstrate that it will _not_ work with
    // QQuickView, whereas it is perfectly fine with QQuickWidget.
    QPalette semiTransparent(QColor(255,0,0,128));
    semiTransparent.setBrush(QPalette::Text, Qt::white);
    semiTransparent.setBrush(QPalette::WindowText, Qt::white);

    m_overlayLabel = new QLabel("This is a\nsemi-transparent\n overlay widget\nwhich is placed\non top\n of the Quick\ncontent.", this);
    m_overlayLabel->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
    m_overlayLabel->setAutoFillBackground(true);
    m_overlayLabel->setPalette(semiTransparent);
    QFont f = font();
    f.setPixelSize(QFontInfo(f).pixelSize()*2);
    f.setWeight(QFont::Bold);
    m_overlayLabel->setFont(f);
    m_overlayLabel->hide();

    m_checkboxOverlayVisible = new QCheckBox(tr("Show widget overlay"));
    connect(m_checkboxOverlayVisible, &QCheckBox::toggled, m_overlayLabel, &QWidget::setVisible);
    layout->addWidget(m_checkboxOverlayVisible);

    m_checkboxTransparent = new QCheckBox(tr("Transparent background in QQuickWidget"));
    connect(m_radioWidget, &QCheckBox::toggled, m_checkboxTransparent, &QWidget::setEnabled);
#ifdef Q_OS_LINUX
    connect(m_checkboxTransparent, &QCheckBox::toggled, this, &MainWindow::onTransparentChanged);
    layout->addWidget(m_checkboxTransparent);
#endif

    setLayout(layout);

    updateView();
}
Exemplo n.º 28
0
void QFontProto::setPixelSize(int pixelSize)
{
  QFont *item = qscriptvalue_cast<QFont*>(thisObject());
  if (item)
    item->setPixelSize(pixelSize);
}
Exemplo n.º 29
0
void WMain::generateTables()
{
    // Amount of columns and rows.
    uint columns = ui -> sb_columns -> value();
    uint rows    = ui -> sb_rows    -> value();

    // Creating pixmaps.
    table = QPixmap(2 * columns * TABLE_CELL_W + 1, rows * TABLE_CELL_H + 1);
    checker = QPixmap(table.size());

    // Filling up 'em with white.
    table.fill();
    checker.fill();

    // Creating painters.
    QPainter p_table(&table);
    QPainter p_checker(&checker);

    // Setting up font size.
    QFont font = p_table.font();
    font.setPixelSize(TABLE_TEXT_SIZE);
    p_table.setFont(font);
    p_checker.setFont(font);

    // Array with available columns.
    std::vector<uint> column_array;
    if (ui -> cb_0 -> isChecked())  column_array.push_back(0);
    if (ui -> cb_1 -> isChecked())  column_array.push_back(1);
    if (ui -> cb_2 -> isChecked())  column_array.push_back(2);
    if (ui -> cb_3 -> isChecked())  column_array.push_back(3);
    if (ui -> cb_4 -> isChecked())  column_array.push_back(4);
    if (ui -> cb_5 -> isChecked())  column_array.push_back(5);
    if (ui -> cb_6 -> isChecked())  column_array.push_back(6);
    if (ui -> cb_7 -> isChecked())  column_array.push_back(7);
    if (ui -> cb_8 -> isChecked())  column_array.push_back(8);
    if (ui -> cb_9 -> isChecked())  column_array.push_back(9);
    if (ui -> cb_10 -> isChecked()) column_array.push_back(10);

    // WTF?
    if (column_array.size() == 0)
        return;

    // Initializing random.
    qsrand(QTime::currentTime().secsTo(QTime()));

    // Creating tables.
    for (uint i = 0; i < columns; i++)
        for (uint j = 0; j < rows; j++)
        {
            // Generating index.
            int index_1 = column_array[qrand() % column_array.size()];
            int index_2 = qrand() % names[index_1].size();

            // Preparing rectangles.
            QRect r_left(2 * i * TABLE_CELL_W, j * TABLE_CELL_H,
                         TABLE_CELL_W,         TABLE_CELL_H);
            QRect r_right((2 * i + 1) * TABLE_CELL_W, j * TABLE_CELL_H,
                          TABLE_CELL_W,               TABLE_CELL_H);

            // Drawing on table.
            p_table.drawText(r_left,
                             Qt::AlignCenter | Qt::AlignHCenter,
                             names[index_1][index_2]);
            p_table.drawRect(r_left);
            p_table.drawRect(r_right);

            // Drawing on checker.
            p_checker.drawText(r_left,
                               Qt::AlignCenter | Qt::AlignHCenter,
                               names[index_1][index_2]);
            p_checker.drawText(r_right,
                               Qt::AlignCenter | Qt::AlignHCenter,
                               letters[index_1][index_2]);
            p_checker.drawRect(r_left);
            p_checker.drawRect(r_right);
        }

    // Saving pictures (for debug).
    #ifdef QT_DEBUG
        table.save("table.png", "png");
        checker.save("checker.png", "png");
    #endif

    // We're ready now!
    ((QLabel*) ui -> sa_task    -> widget()) -> setPixmap(table);
    ((QLabel*) ui -> sa_checker -> widget()) -> setPixmap(checker);
    ui -> t_task    -> setEnabled(true);
    ui -> t_checker -> setEnabled(true);
}
Exemplo n.º 30
0
QFont QgsMapToolLabel::currentLabelFont()
{
  QFont font;

  QgsPalLayerSettings& labelSettings = mCurrentLabel.settings;
  QgsVectorLayer* vlayer = mCurrentLabel.layer;

  QgsRenderContext context = QgsRenderContext::fromMapSettings( mCanvas->mapSettings() );
  if ( mCurrentLabel.valid && vlayer )
  {
    font = labelSettings.format().font();

    QgsFeature f;
    if ( vlayer->getFeatures( QgsFeatureRequest().setFilterFid( mCurrentLabel.pos.featureId ).setFlags( QgsFeatureRequest::NoGeometry ) ).nextFeature( f ) )
    {
      //size
      int sizeIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Size, mCurrentLabel.settings, vlayer );
      if ( sizeIndx != -1 )
      {
        font.setPixelSize( QgsTextRenderer::sizeToPixel( f.attribute( sizeIndx ).toDouble(),
                           context, labelSettings.format().sizeUnit(), true,
                           labelSettings.format().sizeMapUnitScale() ) );
      }

      //family
      int fmIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Family, labelSettings, vlayer );
      if ( fmIndx != -1 )
      {
        font.setFamily( f.attribute( fmIndx ).toString() );
      }

      //underline
      int ulIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Underline, labelSettings, vlayer );
      if ( ulIndx != -1 )
      {
        font.setUnderline( f.attribute( ulIndx ).toBool() );
      }

      //strikeout
      int soIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Strikeout, labelSettings, vlayer );
      if ( soIndx != -1 )
      {
        font.setStrikeOut( f.attribute( soIndx ).toBool() );
      }

      //bold
      int boIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Bold, labelSettings, vlayer );
      if ( boIndx != -1 )
      {
        font.setBold( f.attribute( boIndx ).toBool() );
      }

      //italic
      int itIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Italic, labelSettings, vlayer );
      if ( itIndx != -1 )
      {
        font.setItalic( f.attribute( itIndx ).toBool() );
      }

      // TODO: Add other font data defined values (word spacing, etc.)
    }
  }

  return font;
}