//------------------------------------------------------------------------------
void ctkCoordinatesWidget::updateCoordinate(double coordinate)
{
  int element = -1;
  for (int i = 0; i < this->Dimension; ++i)
    {
    QLayoutItem* item = this->layout()->itemAt(i);
    ctkDoubleSpinBox* spinBox =
      item ? qobject_cast<ctkDoubleSpinBox*>(item->widget()) : 0;
    if ( spinBox && spinBox == this->sender())
      {
      this->Coordinates[i] = coordinate;
      element = i;
      }
    }
  Q_ASSERT(element != -1);
  // Update the last edited history by push first the element.
  for (int i = this->Dimension -1; i > 0; --i)
    {
    if (this->LastUserEditedCoordinates[i] == element)
      {
      this->LastUserEditedCoordinates.swap(i,i-1);
      }
    }
  // What is the oldest coordinate to be edited
  int oldestElement = this->LastUserEditedCoordinates.last();

  if (this->isNormalized())
    {
    // We have to ensure the coordinates are normalized.
    double den = 0.;
    double squaredNorm = this->squaredNorm();
    // Old Values xx + yy + zz = 1
    // New values: x'x' + y'y' + z'z' = 1
    // Say we are changing y into y':
    // x'x' + z'z' = 1 - y'y'
    if (oldestElement != -1 &&
        this->Coordinates[oldestElement] != 0.0 &&
        squaredNorm != 0.0)
      {
      // 1) Normalize only with the oldest user edited value
      // The oldest element is z, that means we try to have
      // x = x' (so that the user doesn't loose the edit he just made on the
      // element (x) he edited before this one (y).
      // Let's pose a the coef to multiply z into z' that keeps the norm to 1
      // xx + z'z' = 1 - y'y' (because x = x')
      // xx + azaz = 1 - y'y' (because z' = az)
      // aa*zz = 1 - y'y' - xx
      // a = sqrt( (1 - y'y' - xx) / zz )
      den = (1. - (squaredNorm -
             this->Coordinates[oldestElement] *
             this->Coordinates[oldestElement])) /
              (this->Coordinates[oldestElement] *
               this->Coordinates[oldestElement]);
      if (den > 0.)
        {
        den = sqrt(den);
        }
      }
    // Maybe 1) failed, then give 2) a chance.
    if (den <= 0)
      {
      oldestElement = -1;
      }
    bool mult = true;
    if (oldestElement == -1)
      {
      // 2) Normalize with all the coordinates
      // Let's pose a the coef to multiply x into x' and z into z' that keeps
      // the norm to 1:
      // axax + azaz = 1 - y'y'
      // aa(xx + zz) = 1 - y'y'
      // a = sqrt( (1 - y'y') / (xx + zz) )
      squaredNorm -= coordinate * coordinate;
      if (squaredNorm != 0.0)
        {
        den = sqrt( (1. - coordinate * coordinate) / squaredNorm);
        }
      else if (this->Dimension > 1)
        {
        mult = false;
        den = sqrt((1. - coordinate*coordinate) / (this->Dimension - 1));
        }
      }
    // Normalize coordinates
    double* normalizedCoordinates = new double[this->Dimension];
    for (int i = 0; i < this->Dimension; ++i)
      {
      if ((i != element && oldestElement == -1) ||
          (i == oldestElement && oldestElement != -1))
        {
        normalizedCoordinates[i] = mult ? this->Coordinates[i] * den : den;
        }
      else
        {
        normalizedCoordinates[i] = this->Coordinates[i];
        }
      }
    this->setCoordinates(normalizedCoordinates);
    delete [] normalizedCoordinates;
    }
  else
    {
    emit coordinatesChanged(this->Coordinates);
    }
}
void OtchetSpravkiPochas::on_pushButton_showReport_clicked()
{
    MyPrint myPrint;
    RowList list;
    list[1] = tr("Сотрудник");
    if(ui->checkBox1->isChecked())
        list[2] = tr("Номер протокола");
    if(ui->checkBox2->isChecked())
        list[3] = tr("Лекций");
    if(ui->checkBox3->isChecked())
        list[4] = tr("Лабор.");
    if(ui->checkBox4->isChecked())
        list[5] = tr("Практич.");
    if(ui->checkBox5->isChecked())
        list[6] = tr("On-line");
    if(ui->checkBox6->isChecked())
        list[7] = tr("Off-line");
    if(ui->checkBox7->isChecked())
        list[8] = tr("Контр. раб.");
    if(ui->checkBox8->isChecked())
        list[9] = tr("Экзам.");
    if(ui->checkBox9->isChecked())
        list[10] = tr("Курс. раб.");
    if(ui->checkBox10->isChecked())
        list[11] = tr("Язык");
    if(ui->checkBox11->isChecked())
        list[12] = tr("Номер справки");
    if(ui->checkBox12->isChecked())
        list[13] = tr("Всего");
    QString header = this->windowTitle() + "<br><br>" \
            "<H3>На " + ui->dateEdit_startReport->date().toString("MMMM yyyy") + " г. </H3>";
    if(!ui->checkBox_detalno->isChecked())
    {
        toPrint = myPrint.print(dal_prepodcontrol->getSpravkiPochasReport(ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt(),
                                                                          ui->dateEdit_startReport->date()),
                                list, header, "", 0);
    }
    else
    {
        QSqlQueryModel* modelMain = dal_prepodcontrol->getSpravkiPochasReport(ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt(),
                                                                              ui->dateEdit_startReport->date());
        QString body;
        body.append("<html><head>"
                    "<link rel='stylesheet' type='text/css' href='format.css'>"
                    "</head><body>");
        body.append("<center><H2>" + header + "</H2></center><br>");
        RowList list2;
        list2[0] = tr("Дата");
        list2[1] = tr("Группа");
        list2[2] = tr("Дисциплина");
        if(ui->checkBox2->isChecked())
            list2[3] = tr("Лекций");
        if(ui->checkBox3->isChecked())
            list2[4] = tr("Лабор.");
        if(ui->checkBox4->isChecked())
            list2[5] = tr("Практич.");
        if(ui->checkBox5->isChecked())
            list2[6] = tr("On-line");
        if(ui->checkBox6->isChecked())
            list2[7] = tr("Off-line");
        if(ui->checkBox7->isChecked())
            list2[8] = tr("Контр. раб.");
        if(ui->checkBox8->isChecked())
            list2[9] = tr("Экзам.");
        if(ui->checkBox9->isChecked())
            list2[10] = tr("Курс. раб.");

        for (int i = 0; i < modelMain->rowCount(); ++i)
        {
            body.append("<p><b>" + modelMain->record(i).value(1).toString() + "</b></p><hr>");
            body.append(myPrint.printOnlyTable(dal_prepodcontrol->getSpravkaPochasDetails(modelMain->record(i).value(14).toInt()), list2, 0));
            body.append("<p><H3>Итого: всего: " +  modelMain->record(i).value(13).toString() + "</H3>");
            if(ui->checkBox2->isChecked())
                body.append(" лекций: " + modelMain->record(i).value(3).toString());
            if(ui->checkBox3->isChecked())
                body.append(" лабор.: " + modelMain->record(i).value(4).toString());
            if(ui->checkBox4->isChecked())
                body.append(" прак.: " + modelMain->record(i).value(5).toString());
            if(ui->checkBox5->isChecked())
                body.append(" on-line: " + modelMain->record(i).value(6).toString());
            if(ui->checkBox6->isChecked())
                body.append(" off-line: " + modelMain->record(i).value(7).toString());
            if(ui->checkBox7->isChecked())
                body.append(" контр. раб.: " + modelMain->record(i).value(8).toString());
            if(ui->checkBox8->isChecked())
                body.append(" экзамен.: " + modelMain->record(i).value(9).toString());
            if(ui->checkBox9->isChecked())
                body.append(" курс. раб.: " + modelMain->record(i).value(10).toString());
            body.append("</p>");
            body.append("<br>");
        }
        body.append("</body></html>");
        QTextDocument *toPrint2 = new QTextDocument;
        toPrint2->addResource(QTextDocument::StyleSheetResource, QUrl( "format.css" ), css->reportCss);
        toPrint2->setHtml(body);
        toPrint = toPrint2;
    }
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName("file.pdf");
    QPrintPreviewDialog *preview = new QPrintPreviewDialog (&printer);
    preview->setAttribute(Qt::WA_DeleteOnClose);
    preview->setWindowFlags(Qt::Widget);
    QList<QPrintPreviewWidget*> list2 = preview->findChildren<QPrintPreviewWidget*>();
    if(!list2.isEmpty()) // paranoiac safety check
        list2.first()->setZoomMode(QPrintPreviewWidget::FitToWidth);
    connect(preview, SIGNAL(paintRequested(QPrinter *)), SLOT(printDocument(QPrinter *)));
    QLayoutItem* item;
    while ((item = ui->verticalLayout->takeAt(0) ) != NULL )
    {
        delete item->widget();
        delete item;
    }
    ui->verticalLayout->addWidget(preview);
    preview->exec();
}
Exemple #3
0
void PreviewWidget::paintEvent( QPaintEvent * )
{
    int i_total = 0, i_offset = 0, i;
    QPainter painter( this );
    QPixmap pixmaps[3];
    for( int i=0; i<3; i++ )
    {
#if HAS_QT5
        pixmaps[i] = bars[i]->grab( bars[i]->contentsRect() );
#else
        pixmaps[i] = QPixmap::grabWidget( bars[i], bars[i]->contentsRect() );
#endif
        for( int j=0; j < bars[i]->layout()->count(); j++ )
        {
            QLayoutItem *item = bars[i]->layout()->itemAt( j );
            if ( !strcmp( item->widget()->metaObject()->className(), "QLabel" ) )
            {
                QPainter eraser( &pixmaps[i] );
                eraser.fillRect( item->geometry(), palette().background() );
                eraser.end();
            }
        }
        pixmaps[i] = pixmaps[i].scaled( size(), Qt::KeepAspectRatio );
    }

    for( i=0; i<3; i++ )
        i_total += pixmaps[i].size().height();

    /* Draw top bars */
    i = ( b_top ) ? 1 : 3;
    for( ; i<3; i++ )
    {
        painter.drawPixmap( pixmaps[i].rect().translated( 0, i_offset ), pixmaps[i] );
        i_offset += pixmaps[i].rect().height();
    }

    /* Draw central area */
    QRect conearea( 0, i_offset, size().width(), size().height() - i_total );
    painter.fillRect( conearea, Qt::black );
    QPixmap cone = QPixmap( ":/logo/vlc128.png" );
    if ( ( conearea.size() - QSize(10, 10) - cone.size() ).isEmpty() )
        cone = cone.scaled( conearea.size() - QSize(10, 10), Qt::KeepAspectRatio );
    if ( cone.size().isValid() )
    {
        painter.drawPixmap( ((conearea.size() - cone.size()) / 2).width(),
                            i_offset + ((conearea.size() - cone.size()) / 2).height(),
                            cone );
    }

    /* Draw bottom bars */
    i_offset += conearea.height();
    for( i = 0 ; i< ((b_top) ? 1 : 3); i++ )
    {
        painter.drawPixmap( pixmaps[i].rect().translated( 0, i_offset ), pixmaps[i] );
        i_offset += pixmaps[i].rect().height();
    }

    /* Draw overlay */
    painter.fillRect( rect(), QColor( 255, 255, 255, 128 ) );

    painter.end();
}
Exemple #4
0
void QLayoutItemProto::invalidate()
{
  QLayoutItem *item = qscriptvalue_cast<QLayoutItem*>(thisObject());
  if (item)
    item->invalidate();
}
Exemple #5
0
/*! \internal

    Controls keyboard navigation and selection on the color grid.
*/
void ColorPickerPopup::keyPressEvent(QKeyEvent *e)
{
    int curRow = 0;
    int curCol = 0;

    bool foundFocus = false;
    for (int j = 0; !foundFocus && j < grid->rowCount(); ++j) {
	for (int i = 0; !foundFocus && i < grid->columnCount(); ++i) {
	    if (widgetAt[j][i] && widgetAt[j][i]->hasFocus()) {
		curRow = j;
		curCol = i;
		foundFocus = true;
		break;
	    }
	}
    }

    switch (e->key()) {
	case Qt::Key_Left:
	    if (curCol > 0) --curCol;
	    else if (curRow > 0) { --curRow; curCol = grid->columnCount() - 1; }
	    break;
	case Qt::Key_Right:
	    if (curCol < grid->columnCount() - 1 && widgetAt[curRow][curCol + 1]) ++curCol;
	    else if (curRow < grid->rowCount() - 1) { ++curRow; curCol = 0; }
	    break;
	case Qt::Key_Up:
	    if (curRow > 0) --curRow;
	    else curCol = 0;
	    break;
	case Qt::Key_Down:
	    if (curRow < grid->rowCount() - 1) {
		QWidget *w = widgetAt[curRow + 1][curCol];
		if (w) {
		    ++curRow;
		} else for (int i = 1; i < grid->columnCount(); ++i) {
		    if (!widgetAt[curRow + 1][i]) {
			curCol = i - 1;
			++curRow;
			break;
		    }
		}
	    }
	    break;
	case Qt::Key_Space:
	case Qt::Key_Return:
	case Qt::Key_Enter: {
	    QWidget *w = widgetAt[curRow][curCol];
	    if (w && w->inherits("ColorPickerItem")) {
		ColorPickerItem *wi = reinterpret_cast<ColorPickerItem *>(w);
		wi->setSelected(true);

		QLayoutItem *layoutItem;
                int i = 0;
		while ((layoutItem = grid->itemAt(i)) != 0) {
		    QWidget *w = layoutItem->widget();
		    if (w && w->inherits("ColorPickerItem")) {
			ColorPickerItem *litem
			    = reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
			if (litem != wi)
			    litem->setSelected(false);
		    }
		    ++i;
		}

		lastSel = wi->color();
		emit selected(wi->color());
		hide();
	    } else if (w && w->inherits("QPushButton")) {
		ColorPickerItem *wi = reinterpret_cast<ColorPickerItem *>(w);
		wi->setSelected(true);

		QLayoutItem *layoutItem;
                int i = 0;
		while ((layoutItem = grid->itemAt(i)) != 0) {
		    QWidget *w = layoutItem->widget();
		    if (w && w->inherits("ColorPickerItem")) {
			ColorPickerItem *litem
			    = reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
			if (litem != wi)
			    litem->setSelected(false);
		    }
		    ++i;
		}

		lastSel = wi->color();
		emit selected(wi->color());
		hide();
	    }
	}
	break;
        case Qt::Key_Escape:
            hide();
        break;
	default:
	    e->ignore();
	    break;
    }

    widgetAt[curRow][curCol]->setFocus();
}
Exemple #6
0
void TextFormatButtons::init(Buttons buttons)
{
  QHBoxLayout *layout = (QHBoxLayout*)this->layout();
  QLayoutItem *child;
  while ((child = layout->takeAt(0)) != 0){
    if (child->widget())
      delete child->widget();
  }

  QFont font = QFont();
  int btnSize = 32;
#ifdef Q_OS_MAC
  btnSize = 38;
#endif
  if (buttons == Legend || buttons == TexLegend){
    QPushButton *buttonCurve = new QPushButton( QPixmap(":/lineSymbol.png"), QString());
    buttonCurve->setFixedWidth(btnSize);
    buttonCurve->setFixedHeight(btnSize);
    buttonCurve->setFont(font);
    layout->addWidget(buttonCurve);
    connect( buttonCurve, SIGNAL(clicked()), this, SLOT(addCurve()) );
  }

  QPushButton *buttonSubscript = new QPushButton(QPixmap(":/index.png"), QString());
  buttonSubscript->setFixedWidth(btnSize);
  buttonSubscript->setFixedHeight(btnSize);
  buttonSubscript->setFont(font);
  layout->addWidget(buttonSubscript);
  connect( buttonSubscript, SIGNAL(clicked()), this, SLOT(addSubscript()) );

  QPushButton *buttonSuperscript = new QPushButton(QPixmap(":/exp.png"), QString());
  buttonSuperscript->setFixedWidth(btnSize);
  buttonSuperscript->setFixedHeight(btnSize);
  buttonSuperscript->setFont(font);
  layout->addWidget(buttonSuperscript);
  connect( buttonSuperscript, SIGNAL(clicked()), this, SLOT(addSuperscript()));

  if (buttons == Equation || buttons == TexLegend){
    QPushButton *buttonFraction = new QPushButton(QPixmap(":/fraction.png"), QString());
    buttonFraction->setFixedWidth(btnSize);
    buttonFraction->setFixedHeight(btnSize);
    buttonFraction->setFont(font);
    layout->addWidget(buttonFraction);
    connect(buttonFraction, SIGNAL(clicked()), this, SLOT(addFraction()));

    QPushButton *buttonSquareRoot = new QPushButton(QPixmap(":/square_root.png"), QString());
    buttonSquareRoot->setFixedWidth(btnSize);
    buttonSquareRoot->setFixedHeight(btnSize);
    buttonSquareRoot->setFont(font);
    layout->addWidget(buttonSquareRoot);
    connect(buttonSquareRoot, SIGNAL(clicked()), this, SLOT(addSquareRoot()));
  }

  QPushButton *buttonLowerGreek = new QPushButton(QString(QChar(0x3B1)));
  buttonLowerGreek->setFont(font);
  buttonLowerGreek->setFixedWidth(btnSize);
  buttonLowerGreek->setFixedHeight(btnSize);
  layout->addWidget(buttonLowerGreek);
  connect( buttonLowerGreek, SIGNAL(clicked()), this, SLOT(showLowerGreek()));

  QPushButton *buttonUpperGreek = new QPushButton(QString(QChar(0x393)));
  buttonUpperGreek->setFont(font);
  buttonUpperGreek->setFixedWidth(btnSize);
  buttonUpperGreek->setFixedHeight(btnSize);
  layout->addWidget(buttonUpperGreek);
  connect( buttonUpperGreek, SIGNAL(clicked()), this, SLOT(showUpperGreek()));

  QPushButton *buttonArrowSymbols = new QPushButton(QString(QChar(0x2192)));
  buttonArrowSymbols->setFont(font);
  buttonArrowSymbols->setFixedWidth(btnSize);
  buttonArrowSymbols->setFixedHeight(btnSize);
  layout->addWidget(buttonArrowSymbols);
  connect( buttonArrowSymbols, SIGNAL(clicked()), this, SLOT(showArrowSymbols()));

  QPushButton *buttonMathSymbols = new QPushButton(QString(QChar(0x222B)));
  buttonMathSymbols->setFont(font);
  buttonMathSymbols->setFixedWidth(btnSize);
  buttonMathSymbols->setFixedHeight(btnSize);
  layout->addWidget(buttonMathSymbols);
  connect( buttonMathSymbols, SIGNAL(clicked()), this, SLOT(showMathSymbols()));

  if (buttons != Plot3D && buttons != Equation && buttons != TexLegend){
    font = this->font();
    font.setBold(true);

    QPushButton *buttonBold = new QPushButton(tr("B","Button bold"));
    buttonBold->setFont(font);
    buttonBold->setFixedWidth(btnSize);
    buttonBold->setFixedHeight(btnSize);
    layout->addWidget(buttonBold);
    connect( buttonBold, SIGNAL(clicked()), this, SLOT(addBold()));

    font = this->font();
    font.setItalic(true);

    QPushButton *buttonItalics = new QPushButton(tr("It","Button italics"));
    buttonItalics->setFont(font);
    buttonItalics->setFixedWidth(btnSize);
    buttonItalics->setFixedHeight(btnSize);
    layout->addWidget(buttonItalics);
    connect( buttonItalics, SIGNAL(clicked()), this, SLOT(addItalics()));

    font = this->font();
    font.setUnderline(true);

    QPushButton *buttonUnderline = new QPushButton(tr("U","Button underline"));
    buttonUnderline->setFont(font);
    buttonUnderline->setFixedWidth(btnSize);
    buttonUnderline->setFixedHeight(btnSize);
    layout->addWidget(buttonUnderline);
    layout->addStretch();
    connect( buttonUnderline, SIGNAL(clicked()), this, SLOT(addUnderline()));
  } else
    layout->addStretch();
}
Exemple #7
0
void QtUnit::mousePressEvent(QMouseEvent *event)
{
    if (event->button() != Qt::LeftButton)
        return;
    if (!this->IsClickable())
        return;
    QVBoxLayout *objGroupLayout = new QVBoxLayout();
    QScrollArea *objScroll = new QScrollArea(objDetail);
    objScroll->setStyleSheet("background-color: rgb(25, 25, 25);");
    objScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    objScroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    QWidget *scrollChild = new QWidget();
    QGridLayout *objGrid = new QGridLayout(scrollChild);
    objGrid->setSizeConstraint(QLayout::SetMinAndMaxSize);

    QLayout *currentLayout = NULL;
    QLayoutItem *child = NULL;
    if (objDetail) {
        if ((currentLayout = objDetail->layout())) {
            while ((child = currentLayout->takeAt(0)) != 0)
                delete child->widget();
            delete currentLayout;
        }
        
    }

    objGroupLayout->addWidget(objScroll);

    QLabel *overlapLab = new QLabel("overlap: ");
    QLabel *overlapVal = new QLabel(QString::number(((Column *)node)->GetOverlap()));
    objGrid->addWidget(overlapLab, 0, 0);
    objGrid->addWidget(overlapVal, 0, 1);

    QLabel *synapsesLab = new QLabel("synaptic details");
    objGrid->addWidget(synapsesLab, 1, 0, 1, 3);
    QLabel *idx = new QLabel("Idx");
    QLabel *coord = new QLabel("Coord");
    QLabel *firing = new QLabel("Firing");
    QLabel *perm = new QLabel("Perm");
    objGrid->addWidget(idx, 2, 0);
    objGrid->addWidget(coord, 2, 1);
    objGrid->addWidget(firing, 2, 2);
    objGrid->addWidget(perm, 2, 3);

    Column *col = (Column *)node;
    DendriteSegment *segment = col->GetProximalDendriteSegment();
    std::vector<Synapse *> syns  = segment->GetSynapses();
    for (int i=0; i<col->GetRecFieldSz(); i++) {
        char synCoordStr[32];
        memset(synCoordStr, 0, sizeof(synCoordStr));
        unsigned int x = syns[i]->GetX(), y = syns[i]->GetY();
        snprintf(synCoordStr, sizeof(synCoordStr), "(%d, %d)", x, y);
        float p = syns[i]->GetPerm();

        QLabel *synIdx = new QLabel(QString("%1: ").arg(i));
        QLabel *synCoordLab = new QLabel(synCoordStr);
        QLabel *synFiring = new QLabel(QString("%1").arg(syns[i]->IsFiring()? 1 : 0));
        QLabel *synPerm = new QLabel(QString("%1: ").arg(p));
        objGrid->addWidget(synIdx, 3+i, 0, 1, 1);
        objGrid->addWidget(synCoordLab, 3+i, 1, 1, 1);
        objGrid->addWidget(synFiring, 3+i, 2, 1, 1);
        objGrid->addWidget(synPerm, 3+i, 3, 1, 1);
    }

    // Note: must add the layout of widget before calling setWidget() or won't
    // be visible.
    objScroll->setWidget(scrollChild);
    objDetail->setLayout(objGroupLayout);
}
Exemple #8
0
void OpenGLWidget::createFractal(QString intName, QString extName)
{
    QLayoutItem* child;
    while ((child = paneLayout->takeAt(0)) != 0)
        child->widget()->deleteLater();
    paneLayout->addWidget(selector);

    fractal = Fractal(intName, extName);

    fractal.init();

    fractal.addComputeVariable("WINDOW_WIDTH", "", WINDOW_WIDTH, WINDOW_WIDTH, WINDOW_WIDTH, WINDOW_WIDTH, false, &WINDOW_WIDTH);
    fractal.copyComputeVariableToRender();
    fractal.addComputeVariable("WINDOW_HEIGHT", "", WINDOW_HEIGHT, WINDOW_HEIGHT, WINDOW_HEIGHT, WINDOW_HEIGHT, false, &WINDOW_HEIGHT);
    fractal.copyComputeVariableToRender();
    fractal.addComputeVariable("BLOCK_WIDTH", "", BLOCK_WIDTH, BLOCK_WIDTH, BLOCK_WIDTH, BLOCK_WIDTH, false, &BLOCK_WIDTH);
    fractal.copyComputeVariableToRender();
    fractal.addComputeVariable("BLOCK_HEIGHT", "", BLOCK_HEIGHT, BLOCK_HEIGHT, BLOCK_HEIGHT, BLOCK_HEIGHT, false, &BLOCK_HEIGHT);
    fractal.copyComputeVariableToRender();
    fractal.addComputeVariable("IMAGE_WIDTH", "", IMAGE_WIDTH, IMAGE_WIDTH, IMAGE_WIDTH, IMAGE_WIDTH, false, &IMAGE_WIDTH);
    fractal.copyComputeVariableToRender();
    fractal.addComputeVariable("IMAGE_HEIGHT", "", IMAGE_HEIGHT, IMAGE_HEIGHT, IMAGE_HEIGHT, IMAGE_HEIGHT, false, &IMAGE_HEIGHT);
    fractal.copyComputeVariableToRender();

    fractal.addComputeVariable("renderOffset", "", renderOffset, renderOffset, renderOffset, renderOffset, false, &renderOffset);
    fractal.addComputeVariable("offset", "", majorOffset, majorOffset, majorOffset, majorOffset, false, &majorOffset);
    fractal.copyComputeVariableToRender();
    fractal.addComputeVariable("ratio", "", RATIO, RATIO, RATIO, RATIO, false, &RATIO);
    fractal.addComputeVariable("zoom", "Zoom", zoom, zoom, 0.0f, float(std::pow(2, 64)), true, &zoom);

    m_vao.bind();

    m_vvbo.create();
    m_vvbo.bind();
    m_vvbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
    m_vvbo.allocate(vertices.data(), vertices.size() * sizeof(float));

    m_ebo.create();
    m_ebo.bind();
    m_ebo.setUsagePattern(QOpenGLBuffer::StaticDraw);
    m_ebo.allocate(indices.data(), indices.size() * sizeof(int));

    m_vao.release();

    m_vvbo.release();
    m_ebo.release();

    fractal.computeProgram->bind();
    glBindImageTexture(0, tex[0], 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32F);
    fractal.computeProgram->release();

    fractal.renderProgram->bind();
    m_vao.bind();
    m_vvbo.bind();
    fractal.renderProgram->enableAttributeArray("position");
    fractal.renderProgram->setAttributeBuffer("position", GL_FLOAT, 0, 3);
    m_vvbo.release();
    m_vao.release();
    glBindImageTexture(0, tex[0], 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32F);
    fractal.renderProgram->release();

    rendermodeLR = ALL;
}
void RunningScriptsWidget::setRunningScripts(const QStringList& list) {
    setUpdatesEnabled(false);
    QLayoutItem* widget;
    while ((widget = ui->scriptListWidget->layout()->takeAt(0)) != NULL) {
        delete widget->widget();
        delete widget;
    }
    QHash<QString, int> hash;
    const int CLOSE_ICON_HEIGHT = 12;
    for (int i = 0; i < list.size(); i++) {
        if (!hash.contains(list.at(i))) {
            hash.insert(list.at(i), 1);
        }
        QWidget* row = new QWidget(ui->scriptListWidget);
        row->setLayout(new QHBoxLayout(row));

        QUrl url = QUrl(list.at(i));
        QLabel* name = new QLabel(url.fileName(), row);
        if (hash.find(list.at(i)).value() != 1) {
            name->setText(name->text() + "(" + QString::number(hash.find(list.at(i)).value()) + ")");
        }
        ++hash[list.at(i)];
        QPushButton* closeButton = new QPushButton(row);
        closeButton->setFlat(true);
        closeButton->setIcon(
            QIcon(QPixmap(Application::resourcesPath() + "images/kill-script.svg").scaledToHeight(CLOSE_ICON_HEIGHT)));
        closeButton->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred));
        closeButton->setStyleSheet("border: 0;");
        closeButton->setCursor(Qt::PointingHandCursor);

        connect(closeButton, SIGNAL(clicked()), &_signalMapper, SLOT(map()));
        _signalMapper.setMapping(closeButton, url.toString());

        row->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));

        row->layout()->setContentsMargins(4, 4, 4, 4);
        row->layout()->setSpacing(0);

        row->layout()->addWidget(name);
        row->layout()->addWidget(closeButton);

        row->setToolTip(url.toString());

        QFrame* line = new QFrame(row);
        line->setFrameShape(QFrame::HLine);
        line->setStyleSheet("color: #E1E1E1; margin-left: 6px; margin-right: 6px;");

        ui->scriptListWidget->layout()->addWidget(row);
        ui->scriptListWidget->layout()->addWidget(line);
    }


    ui->noRunningScriptsLabel->setVisible(list.isEmpty());
    ui->reloadAllButton->setVisible(!list.isEmpty());
    ui->stopAllButton->setVisible(!list.isEmpty());

    ui->scriptListWidget->updateGeometry();
    setUpdatesEnabled(true);
    Application::processEvents();
    repaint();
}
Exemple #10
0
/**
 * The purpose of this function is to make sure that widgets are not laid out outside its layout.
 * E.g. the layoutItemRect margins are only meant to take of the surrounding margins/spacings.
 * However, if the margin is 0, it can easily cover the area of a widget above it.
 */
void QBoxLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *bottom) const
{
    int l = leftMargin;
    int t = topMargin;
    int r = rightMargin;
    int b = bottomMargin;
#ifdef Q_OS_MAC
    Q_Q(const QBoxLayout);
    if (horz(dir)) {
        QBoxLayoutItem *leftBox = 0;
        QBoxLayoutItem *rightBox = 0;

        if (left || right) {
            leftBox = list.value(0);
            rightBox = list.value(list.count() - 1);
            if (dir == QBoxLayout::RightToLeft)
                qSwap(leftBox, rightBox);

            int leftDelta = 0;
            int rightDelta = 0;
            if (leftBox) {
                QLayoutItem *itm = leftBox->item;
                if (QWidget *w = itm->widget())
                    leftDelta = itm->geometry().left() - w->geometry().left();
            }
            if (rightBox) {
                QLayoutItem *itm = rightBox->item;
                if (QWidget *w = itm->widget())
                    rightDelta = w->geometry().right() - itm->geometry().right();
            }
            QWidget *w = q->parentWidget();
            Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QApplication::layoutDirection();
            if (layoutDirection == Qt::RightToLeft)
                qSwap(leftDelta, rightDelta);

            l = qMax(l, leftDelta);
            r = qMax(r, rightDelta);
        }

        int count = top || bottom ? list.count() : 0;
        for (int i = 0; i < count; ++i) {
            QBoxLayoutItem *box = list.at(i);
            QLayoutItem *itm = box->item;
            QWidget *w = itm->widget();
            if (w) {
                QRect lir = itm->geometry();
                QRect wr = w->geometry();
                if (top)
                    t = qMax(t, lir.top() - wr.top());
                if (bottom)
                    b = qMax(b, wr.bottom() - lir.bottom());
            }
        }
    } else {    // vertical layout
        QBoxLayoutItem *topBox = 0;
        QBoxLayoutItem *bottomBox = 0;

        if (top || bottom) {
            topBox = list.value(0);
            bottomBox = list.value(list.count() - 1);
            if (dir == QBoxLayout::BottomToTop) {
                qSwap(topBox, bottomBox);
            }

            if (top && topBox) {
                QLayoutItem *itm = topBox->item;
                QWidget *w = itm->widget();
                if (w)
                    t = qMax(t, itm->geometry().top() - w->geometry().top());
            }

            if (bottom && bottomBox) {
                QLayoutItem *itm = bottomBox->item;
                QWidget *w = itm->widget();
                if (w)
                    b = qMax(b, w->geometry().bottom() - itm->geometry().bottom());
            }
        }

        int count = left || right ? list.count() : 0;
        for (int i = 0; i < count; ++i) {
            QBoxLayoutItem *box = list.at(i);
            QLayoutItem *itm = box->item;
            QWidget *w = itm->widget();
            if (w) {
                QRect lir = itm->geometry();
                QRect wr = w->geometry();
                if (left)
                    l = qMax(l, lir.left() - wr.left());
                if (right)
                    r = qMax(r, wr.right() - lir.right());
            }
        }
    }
#endif
    if (left)
        *left = l;
    if (top)
        *top = t;
    if (right)
        *right = r;
    if (bottom)
        *bottom = b;
}
void
RadioWidget::refresh( const unicorn::Session& session )
{
    if ( session.isValid() )
    {
        m_movie->stop();

        if ( session.youRadio() )
        {
            unicorn::UserSettings us( session.user().name() );
            QString stationUrl = us.value( "lastStationUrl", "" ).toString();
            QString stationTitle = us.value( "lastStationTitle", tr( "A Radio Station" ) ).toString();

            ui->nowPlayingFrame->setVisible( !stationUrl.isEmpty() );

            RadioStation lastStation( stationUrl );
            lastStation.setTitle( stationTitle );

            ui->lastStation->setStation( lastStation, stationTitle );
            ui->lastStation->setObjectName( "station" );
            style()->polish( ui->lastStation );

            ui->library->setStation( RadioStation::library( session.user() ), tr( "My Library Radio" ), tr( "Music you know and love" ) );
            ui->mix->setStation( RadioStation::mix( session.user() ), tr( "My Mix Radio" ), tr( "Your library plus new music" ) );
            ui->rec->setStation( RadioStation::recommendations( session.user() ), tr( "My Recommended Radio" ), tr( "New music from Last.fm" ) );

            ui->friends->setStation( RadioStation::friends( session.user() ), tr( "My Friends' Radio" ), tr( "Music your friends like" ) );
            ui->neighbours->setStation( RadioStation::neighbourhood( session.user() ), tr( "My Neighbourhood Radio" ), tr ( "Music from listeners like you" ) );

            if ( m_currentUsername != session.user().name() )
            {
                m_currentUsername = session.user().name();

                // clear the recent stations
                QLayout* recentStationsLayout = ui->recentStations->layout();
                while ( recentStationsLayout->count() )
                {
                    QLayoutItem* item = recentStationsLayout->takeAt( 0 );
                    delete item->widget();
                    delete item;
                }

                // fetch recent stations
                connect( session.user().getRecentStations( MAX_RECENT_STATIONS ), SIGNAL(finished()), SLOT(onGotRecentStations()));
            }

            ui->stackedWidget->setCurrentWidget( ui->mainPage );
        }
        else
        {
            ui->listen->setVisible( session.registeredWebRadio() );

            ui->stackedWidget->setCurrentWidget( ui->nonSubPage );

            ui->title->setText( tr( "Subscribe to listen to radio, only %1 a month" ).arg( session.subscriptionPriceString() ) );
            ui->subscribe->setVisible( session.subscriberRadio() );
        }
    }
    else
    {
        ui->stackedWidget->setCurrentWidget( ui->spinnerPage );
        m_movie->start();
    }
}
void VirshGui::populateVMInfos(string vmname)
{
    VMStatus vmstatus = vmlist[vmname].getStatus();
    string strstatus = vmlist[vmname].statusToString(vmstatus);
    string memory = vmlist[vmname].getMemory();
    string vmxml = vmlist[vmname].dumpXML();
    string cpuCount = vmlist[vmname].getCPUCount();
    string ostype = vmlist[vmname].getOSType();
    string arch = vmlist[vmname].getArch();
    vector<string> bootDevs = vmlist[vmname].getBootDevs();
    vector<string> hvFeatures = vmlist[vmname].getHVFeatures();
    vector<string> cpuFeatures = vmlist[vmname].getCPUFeatures();

    string bootDevStr = join(bootDevs, ", ");
    string hvFeatureStr = join(hvFeatures, ", ");
    string cpuFeatureStr = join(cpuFeatures, ", ");

    if (vmstatus == VMStatus::shutoff) {
        ui->startStopButton->setText("VM starten");
        ui->startStopButton->setEnabled(true);
        ui->shutdownButton->setDisabled(true);
        ui->rebootButton->setDisabled(true);
        ui->virtViewerButton->setDisabled(true);
    } else if (vmstatus == VMStatus::running) {
        ui->startStopButton->setText("VM ausschalten");
        ui->startStopButton->setEnabled(true);
        ui->shutdownButton->setEnabled(true);
        ui->rebootButton->setEnabled(true);
        ui->virtViewerButton->setEnabled(true);
    } else {
        ui->startStopButton->setText("keine Aktion");
        ui->startStopButton->setDisabled(true);
        ui->shutdownButton->setDisabled(true);
        ui->rebootButton->setDisabled(true);
        ui->virtViewerButton->setDisabled(true);
    }

    while (ui->snapshotsTabLayout->count() > 0) {
        QLayoutItem *item = ui->snapshotsTabLayout->takeAt(0);
        delete item->widget();
        delete item;
    }

    int snapshotTableCount = 0;
    for (auto hdd : vmlist[vmname].getHDDImages()) {
        int row = 0;
        QGroupBox *hddGroupBox = new QGroupBox(QString::fromStdString(hdd.getPath()));
        hddGroupBox->setFlat(false);

        QVBoxLayout *hddVBox = new QVBoxLayout;
        QTableWidget *snapshotTable = new QTableWidget(0, 5, this);
        snapshotTable->setSelectionMode(QAbstractItemView::SingleSelection);
        snapshotTable->setHorizontalHeaderLabels(QStringList() << "ID" << "Tag" << "VM Size" << "Date" << "VM Clock");
        snapshotTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
        //snapshotTable->setColumnWidth(0, 45);
        snapshotTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
        snapshotTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
        snapshotTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
        snapshotTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
        snapshotTable->verticalHeader()->hide();
        snapshotTable->setAlternatingRowColors(true);
        //snapshotTable->setSortingEnabled(true);
        snapshotTable->setEditTriggers(QTableWidget::NoEditTriggers);
        connect(snapshotTable, &QTableWidget::cellPressed, [this, snapshotTableCount](){ clearSnapshotSelectionsExcept(snapshotTableCount); });
        snapshotTableCount++;

        for (auto snapshot : hdd.getSnapshots()) {
            snapshotTable->setRowCount(row + 1);
            QTableWidgetItem *id = new QTableWidgetItem(
                    QString::fromStdString(snapshot.getID()));
            QTableWidgetItem *tag = new QTableWidgetItem(
                    QString::fromStdString(snapshot.getTag()));
            QTableWidgetItem *size = new QTableWidgetItem(
                    QString::fromStdString(snapshot.getSize()));
            QTableWidgetItem *date = new QTableWidgetItem(
                    QString::fromStdString(snapshot.getDate()));
            QTableWidgetItem *clock = new QTableWidgetItem(
                    QString::fromStdString(snapshot.getClock()));

            snapshotTable->setItem(row, 0, id);
            snapshotTable->setItem(row, 1, tag);
            snapshotTable->setItem(row, 2, size);
            snapshotTable->setItem(row, 3, date);
            snapshotTable->setItem(row, 4, clock);

            row++;
        }
        hddVBox->addWidget(snapshotTable);

        QHBoxLayout *addSnapHBox = new QHBoxLayout;
        QLineEdit *addSnapNameEdit = new QLineEdit;
        QPushButton *addSnapButton = new QPushButton;
        addSnapButton->setText("Snapshot erstellen");
        addSnapButton->setEnabled(false);
        string hddPath = hdd.getPath();
        connect(addSnapNameEdit, &QLineEdit::textChanged, [this, addSnapButton, addSnapNameEdit](){ toggleAddSnapshotButton(addSnapButton, addSnapNameEdit); });
        connect(addSnapButton, &QPushButton::clicked, [this, hddPath, vmname, addSnapNameEdit](){ createSnapshot(hddPath, vmname, addSnapNameEdit->text().toStdString()); });
        addSnapHBox->addWidget(addSnapNameEdit);
        addSnapHBox->addWidget(addSnapButton);

        hddVBox->addLayout(addSnapHBox);
        hddGroupBox->setLayout(hddVBox);
        ui->snapshotsTabLayout->addWidget(hddGroupBox);
    }

    QPushButton *applySnapshotButton = new QPushButton("Snapshot Anwenden", this);
    connect(applySnapshotButton, SIGNAL(clicked(bool)), this, SLOT(applySnapshot()));
    //connect(applySnapshotButton, &QPushButton::clicked, [this](){ clearSnapshotSelectionsExcept(1); });
    ui->snapshotsTabLayout->addWidget(applySnapshotButton);

    ui->xmlDisplay->setText(QString::fromStdString(vmxml));
    ui->vmnameLabel->setText(QString::fromStdString(vmname));
    ui->statusLabel->setText(QString::fromStdString(strstatus));
    ui->memoryLabel->setText(QString::fromStdString(memory));
    ui->cpucountLabel->setText(QString::fromStdString(cpuCount));
    ui->typeLabel->setText(QString::fromStdString(ostype));
    ui->archLabel->setText(QString::fromStdString(arch));
    ui->bootdevLabel->setText(QString::fromStdString(bootDevStr));
    ui->hvFeaturesLabel->setText(QString::fromStdString(hvFeatureStr));
    ui->hvFeaturesLabel->setWordWrap(true);
    ui->cpuFeaturesLabel->setText(QString::fromStdString(cpuFeatureStr));
    ui->cpuFeaturesLabel->setWordWrap(true);
}
// Arranges widgets and returns height required.
int PackedLayout::arrange(const QRect& rect, bool set) const
{
    int x = rect.x();
    int y = rect.y();
    int yrow = 0;
    QList<QRect> posn;
    int end = mItems.count();
    QList<QLayoutItem*> items;
    for (int i = 0;  i < end;  ++i)
    {
        QLayoutItem* item = mItems[i];
        if (item->isEmpty())
            continue;
        QSize size = item->sizeHint();
        int right = x + size.width();
        if (right > rect.right()  &&  x > rect.x())
        {
            x = rect.x();
            y = y + yrow + spacing();
            right = x + size.width();
            yrow = size.height();
        }
        else
            yrow = qMax(yrow, size.height());
        items.append(item);
        posn.append(QRect(QPoint(x, y), size));
        x = right + spacing();
    }
    if (set)
    {
        int count = items.count();
        if (mAlignment == Qt::AlignLeft)
        {
            // Left aligned: no position adjustment needed
            // Set the positions of all the layout items
            for (int i = 0;  i < count;  ++i)
                items[i]->setGeometry(posn[i]);
        }
        else
        {
            // Set the positions of all the layout items
            for (int i = 0;  i < count; )
            {
                // Adjust item positions a row at a time
                y = posn[i].y();
                int last;   // after last item in this row
                for (last = i + 1;  last < count && posn[last].y() == y;  ++last) ;
                int n = last - i;   // number of items in this row
                int free = rect.right() - posn[last - 1].right();
                switch (mAlignment)
                {
                    case Qt::AlignJustify:
                        if (n == 1)
                        {
                            items[i]->setGeometry(posn[i]);
                            ++i;
                        }
                        else if (n > 1)
                        {
                            for (int j = 0;  i < last;  ++j, ++i)
                                items[i]->setGeometry(QRect(QPoint(posn[i].x() + (free * j)/(n - 1), y), posn[i].size()));
                        }
                        break;
                    case Qt::AlignHCenter:
                        free /= 2;
                        // fall through to AlignRight
                    case Qt::AlignRight:
                        for ( ;  i < last;  ++i)
                            items[i]->setGeometry(QRect(QPoint(posn[i].x() + free, y), posn[i].size()));
                        break;
                    default:
                        break;
                }
            }
        }
    }
    return y + yrow - rect.y();
}
Exemple #14
0
void BorderLayout::setGeometry(const QRect &rect)
{
    ItemWrapper *center = 0;
    int eastWidth = 0;
    int westWidth = 0;
    int northHeight = 0;
    int southHeight = 0;
    int centerHeight = 0;
    int i;

    QLayout::setGeometry(rect);

    for (i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        if (position == North) {
            item->setGeometry(QRect(rect.x(), northHeight, rect.width(),
                                    item->sizeHint().height()));

            northHeight += item->geometry().height() + spacing();
        } else if (position == South) {
            item->setGeometry(QRect(item->geometry().x(),
                                    item->geometry().y(), rect.width(),
                                    item->sizeHint().height()));

            southHeight += item->geometry().height() + spacing();

            item->setGeometry(QRect(rect.x(),
                                    rect.y() + rect.height() - southHeight + spacing(),
                                    item->geometry().width(),
                                    item->geometry().height()));
        } else if (position == Center) {
            center = wrapper;
        }
    }

    centerHeight = rect.height() - northHeight - southHeight;

    for (i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        if (position == West) {
            item->setGeometry(QRect(rect.x() + westWidth, northHeight,
                                    item->sizeHint().width(), centerHeight));

            westWidth += item->geometry().width() + spacing();
        } else if (position == East) {
            item->setGeometry(QRect(item->geometry().x(), item->geometry().y(),
                                    item->sizeHint().width(), centerHeight));

            eastWidth += item->geometry().width() + spacing();

            item->setGeometry(QRect(
                                  rect.x() + rect.width() - eastWidth + spacing(),
                                  northHeight, item->geometry().width(),
                                  item->geometry().height()));
        }
    }

    if (center)
        center->item->setGeometry(QRect(westWidth, northHeight,
                                        rect.width() - eastWidth - westWidth,
                                        centerHeight));
}
void EntitieCustomeWidget::timerEvent(){
    if(core->getFocus()!=-1){
        if(this->curFocus != core->getFocus() || (core->getFocusObj()!=this->curObj)){
            this->curFocus = core->getFocus();
            this->curObj = core->getFocusObj();
            if(core->getFocusObj()){
                if(core->getFocus()<core->getEntitieCount()){
                    Entitie* e = core->getEntitieAt(core->getFocus());
                    this->ClearWidget();

                    this->entitieName = new QLabel("Название сущности:");
                    this->tb = new QLineEdit();

                    // Label
                    this->tb->setMaxLength(50);
                    this->tb->setText(QString::fromStdString(e->getID()));

                    // Layout
                    this->setLayout(qbl);

                    // Добавление widget'ов
                    this->qbl->addWidget(this->entitieName);
                    this->qbl->addWidget(this->tb);
                    for(int i=0; i<e->fieldCount(); i++){
                        LineOfField* lf = new LineOfField(this, e, e->fieldAt(i),this);
                        this->fildlist->push_back(lf);
                        this->qbl->addWidget(lf);
                    }
                    this->addButton = new QPushButton("Добавить поле");
                    this->qbl->addWidget(this->addButton);
                    this->qbl->addStretch();
                    QObject::connect(this->addButton,SIGNAL(clicked()),this,SLOT(buttonAdd()));
                }
            }else{
                if(core->getFocus()<core->getRelationCount()){
                    Relation* r = core->getRelationAt(core->getFocus());
                    this->ClearWidget();

                    this->entitieName = new QLabel("Название связи:");
                    this->tb = new QLineEdit();
                    // Label
                    this->tb->setMaxLength(50);
                    this->tb->setText(QString::fromStdString(r->getID()));

                    this->qbl->addWidget(this->entitieName);
                    this->qbl->addWidget(this->tb);
                    this->qbl->addWidget(new QLabel("Ключевое поле"));
                    this->key = new QLineEdit("Ключ");
                    this->key->setText(QString::fromStdString(r->getKey()));
                    this->qbl->addWidget(this->key);
                    //==========================================
                    this->ml = new QCheckBox("Множественная связь слева");
                    this->ml->setChecked(r->getMulL());
                    this->qbl->addWidget(ml);
                    //==========================================
                    this->mr = new QCheckBox("Множественная связь справа");
                    this->mr->setChecked(r->getMulR());
                    this->qbl->addWidget(mr);
                    //==========================================
                    this->al = new QCheckBox("Абстрактная связь слева");
                    this->al->setChecked(r->getAbsL());
                    this->qbl->addWidget(al);
                    //==========================================
                    this->ar = new QCheckBox("Абстрактная связь справа");
                    this->ar->setChecked(r->getAbsR());
                    this->qbl->addWidget(ar);
                    //==========================================
                    this->qbl->addStretch();
                    this->setLayout(qbl);
                }
            }
        }
    }else{
        this->curFocus = -1;
        this->curObj = true;
        while(this->layout()->count()>0){
            QLayoutItem* item = this->layout()->itemAt(0);
            this->layout()->removeItem( item );
            this->layout()->removeWidget(item->widget());
            delete item->widget();
            delete item;
            this->layout()->update();
        }
    }
}
Exemple #16
0
void QgsMessageBarItem::writeContent()
{
  if ( mLayout == 0 )
  {
    mLayout = new QHBoxLayout( this );
    mLayout->setContentsMargins( 0, 0, 0, 0 );
    mTextEdit = 0;
    mLblIcon = 0;
  }

  // ICON
  if ( mLblIcon == 0 )
  {
    mLblIcon = new QLabel( this );
    mLayout->addWidget( mLblIcon );
  }
  QIcon icon;
  if ( !mUserIcon.isNull() )
  {
    icon = mUserIcon;
  }
  else
  {
    QString msgIcon( "/mIconInfo.png" );
    switch ( mLevel )
    {
      case QgsMessageBar::CRITICAL:
        msgIcon = QString( "/mIconCritical.png" );
        break;
      case QgsMessageBar::WARNING:
        msgIcon = QString( "/mIconWarn.png" );
        break;
      case QgsMessageBar::SUCCESS:
        msgIcon = QString( "/mIconSuccess.png" );
        break;
      default:
        break;
    }
    icon = QgsApplication::getThemeIcon( msgIcon );
  }
  mLblIcon->setPixmap( icon.pixmap( 24 ) );

  // TITLE AND TEXT
  if ( mTitle.isEmpty() && mText.isEmpty() )
  {
    if ( mTextEdit != 0 )
    {
      delete mTextEdit;
      mTextEdit = 0;
    }
  }
  else
  {
    if ( mTextEdit == 0 )
    {
      mTextEdit = new QTextEdit( this );
      mTextEdit->setObjectName( "textEdit" );
      mTextEdit->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Maximum );
      mTextEdit->setReadOnly( true );
      mTextEdit->setFrameShape( QFrame::NoFrame );
      // stylesheet set here so Qt-style substitued scrollbar arrows can show within limited height
      // adjusts to height of font set in app options
      mTextEdit->setStyleSheet( "QTextEdit { background-color: rgba(0,0,0,0); margin-top: 0.25em; max-height: 1.75em; min-height: 1.75em; } "
                                "QScrollBar { background-color: rgba(0,0,0,0); } "
                                "QScrollBar::add-page,QScrollBar::sub-page,QScrollBar::handle { background-color: rgba(0,0,0,0); color: rgba(0,0,0,0); } "
                                "QScrollBar::up-arrow,QScrollBar::down-arrow { color: rgb(0,0,0); } " );
      mLayout->addWidget( mTextEdit );
    }
    QString content = mText;
    if ( !mTitle.isEmpty() )
    {
      // add ':' to end of title
      QString t = mTitle.trimmed();
      if ( !content.isEmpty() && !t.endsWith( ':' ) && !t.endsWith( ": " ) )
        t += ": ";
      content.prepend( QLatin1String( "<b>" ) + t + " </b>" );
    }
    mTextEdit->setText( content );
  }

  // WIDGET
  if ( mWidget != 0 )
  {
    QLayoutItem *item = mLayout->itemAt( 2 );
    if ( !item || item->widget() != mWidget )
    {
      mLayout->addWidget( mWidget );
    }
  }

  // STYLESHEET
  if ( mLevel == QgsMessageBar::SUCCESS )
  {
    mStyleSheet = "QgsMessageBar { background-color: #dff0d8; border: 1px solid #8e998a; } "
                  "QLabel,QTextEdit { color: black; } ";
  }
  else if ( mLevel == QgsMessageBar::CRITICAL )
  {
    mStyleSheet = "QgsMessageBar { background-color: #d65253; border: 1px solid #9b3d3d; } "
                  "QLabel,QTextEdit { color: white; } ";
  }
  else if ( mLevel == QgsMessageBar::WARNING )
  {
    mStyleSheet = "QgsMessageBar { background-color: #ffc800; border: 1px solid #e0aa00; } "
                  "QLabel,QTextEdit { color: black; } ";
  }
  else if ( mLevel == QgsMessageBar::INFO )
  {
    mStyleSheet = "QgsMessageBar { background-color: #e7f5fe; border: 1px solid #b9cfe4; } "
                  "QLabel,QTextEdit { color: #2554a1; } ";
  }
  mStyleSheet += "QLabel#mItemCount { font-style: italic; }";
}
Exemple #17
0
/*!
  Insert a new item for a plot item
  \param plotItem Plot item
  \param legendItem New legend item
  \note The parent of item will be changed to QwtLegend::contentsWidget()
*/
void QwtLegend::insert(const QwtLegendItemManager *plotItem, QWidget *legendItem)
{
    if ( legendItem == NULL || plotItem == NULL )
        return;

    QWidget *contentsWidget = d_data->view->contentsWidget;

    if ( legendItem->parent() != contentsWidget )
    {
#if QT_VERSION >= 0x040000
        legendItem->setParent(contentsWidget);
#else
        legendItem->reparent(contentsWidget, QPoint(0, 0));
#endif
    }

    legendItem->show();

    d_data->map.insert(plotItem, legendItem);

    layoutContents();

    if ( contentsWidget->layout() )
    {
#if QT_VERSION >= 0x040000
        contentsWidget->layout()->addWidget(legendItem);
#endif

        // set tab focus chain

        QWidget *w = NULL;

#if QT_VERSION < 0x040000
        QLayoutIterator layoutIterator = 
            contentsWidget->layout()->iterator();
        for ( QLayoutItem *item = layoutIterator.current();
            item != 0; item = ++layoutIterator)
        {
#else
        for (int i = 0; i < contentsWidget->layout()->count(); i++)
        {
            QLayoutItem *item = contentsWidget->layout()->itemAt(i);
#endif
            if ( w && item->widget() )
            {
                QWidget::setTabOrder(w, item->widget());
                w = item->widget();
            }
        }
    }
    if ( parentWidget() && parentWidget()->layout() == NULL )
    {
       /*
          updateGeometry() doesn't post LayoutRequest in certain
          situations, like when we are hidden. But we want the
          parent widget notified, so it can show/hide the legend
          depending on its items.
        */
#if QT_VERSION < 0x040000
        QApplication::postEvent(parentWidget(),
            new QEvent(QEvent::LayoutHint));
#else
        QApplication::postEvent(parentWidget(),
            new QEvent(QEvent::LayoutRequest));
#endif
    }
}

/*!
  Find the widget that represents a plot item

  \param plotItem Plot item
  \return Widget on the legend, or NULL
*/
QWidget *QwtLegend::find(const QwtLegendItemManager *plotItem) const
{
    return d_data->map.find(plotItem);
}

/*!
  Find the widget that represents a plot item

  \param plotItem Plot item
  \return Widget on the legend, or NULL
*/
QwtLegendItemManager *QwtLegend::find(const QWidget *legendItem) const
{
    return d_data->map.find(legendItem);
}

/*! 
   Find the corresponding item for a plotItem and remove it 
   from the item list.

   \param plotItem Plot item
*/
void QwtLegend::remove(const QwtLegendItemManager *plotItem)
{ 
    QWidget *legendItem = d_data->map.find(plotItem);
    d_data->map.remove(legendItem); 
    delete legendItem;
}
QWidget *QDockWidgetLayout::widgetForRole(Role r) const
{
    QLayoutItem *item = item_list.at(r);
    return item == 0 ? 0 : item->widget();
}
void MainWindow::setGrip()
{
    QLayoutIterator it = lay->iterator();
    QLayoutItem *lastItem = NULL;
    for (;;){
        QLayoutItem *item = it.current();
        if (item == NULL)
            break;
        lastItem = item;
        if (++it == NULL)
            break;
    }
    if (lastItem == NULL)
        return;
    if (lastItem->layout() && (lastItem->layout() == h_lay)){
        QLayoutIterator it = h_lay->iterator();
        for (;;){
            QLayoutItem *item = it.current();
            if (item == NULL)
                break;
            QWidget *w = item->widget();
            if (w && (w != m_grip))
                return;
            if (++it == NULL)
                break;
        }
    }
    QWidget *oldWidget = NULL;
    QWidget *w = lastItem->widget();
    if (m_grip){
        delete m_grip;
        m_grip = NULL;
    }
    if (h_lay){
        QLayoutIterator it = h_lay->iterator();
        for (;;){
            QLayoutItem *item = it.current();
            if (item == NULL)
                break;
            oldWidget = item->widget();
            if (oldWidget)
                break;
            if (++it == NULL)
                break;
        }
        delete h_lay;
        h_lay = NULL;
        it = lay->iterator();
        for (;;){
            QLayoutItem *item = it.current();
            if (item == NULL)
                break;
            lastItem = item;
            if (++it == NULL)
                break;
        }
        if (lastItem)
            w = lastItem->widget();
    }
    if (oldWidget && w){
        int index = lay->findWidget(w);
        lay->insertWidget(index - 1, oldWidget);
    }
    if (w && (w->sizePolicy().verData() == QSizePolicy::Fixed) && !statusBar()->isVisible()){
        w->reparent(this, QPoint());
        w->reparent(main, QPoint());
        h_lay = new QHBoxLayout(lay);
        h_lay->addWidget(w);
        h_lay->addSpacing(2);
        m_grip = new QSizeGrip(main);
#ifdef WIN32
        m_grip->installEventFilter(this);
#endif
        m_grip->setFixedSize(m_grip->sizeHint());
        h_lay->addWidget(m_grip, 0, AlignBottom);
        w->show();
        m_grip->show();
    }
}
Exemple #20
0
void FlagLayout::setGeometry(const QRect &rect)
{
    int topHeight = 0;
    int bottomHeight = 0;

    QLayout::setGeometry(rect);

    // left side
    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        if (position == TopLeft) {
            topHeight += spacing();
            item->setGeometry(QRect(rect.x() + spacing(), topHeight, 
                                    item->sizeHint().width(), item->sizeHint().height()));

            topHeight += item->geometry().height();
        } else if (position == BottomLeft) {
            bottomHeight += item->geometry().height() + spacing();
            item->setGeometry(QRect(rect.x() + spacing(), rect.height() - bottomHeight, 
                                    item->sizeHint().width(), item->sizeHint().height()));
        }
    }

    // right side
    topHeight = 0;
    bottomHeight = 0;
    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        int rightpos = item->sizeHint().width() + spacing();
        if (position == TopRight) {
            topHeight += spacing();
            item->setGeometry(QRect(rect.x() + rect.width() - rightpos, topHeight, 
                                    item->sizeHint().width(), item->sizeHint().height()));

            topHeight += item->geometry().height();
        } else if (position == BottomRight) {
            bottomHeight += item->geometry().height() + spacing();
            item->setGeometry(QRect(rect.x() + rect.width() - rightpos, rect.height() - bottomHeight, 
                                    item->sizeHint().width(), item->sizeHint().height()));
        }
    }
}
Exemple #21
0
void PhotoDrop::reorderPhotos()
{
	std::cerr << "PhotoDrop::reorderPhotos()";
	std::cerr << std::endl;

	/* now move the qwidgets around */
	QLayout *alayout = layout();
	QGridLayout *glayout = dynamic_cast<QGridLayout *>(alayout);
	if (!glayout)
	{
		std::cerr << "PhotoDrop::reorderPhotos() not GridLayout... not much we can do!";
		std::cerr << std::endl;
		return;
	}

	/* grab the first PhotoItem - and get it size */
	std::map<gridIndex, PhotoItem *> photoItems;
	std::map<gridIndex, PhotoItem *>::iterator pit;

	int count = glayout->count();
	int i = 0;
	for(i = 0; i < count; i++)
	{
		QLayoutItem *litem = glayout->itemAt(i);
		if (!litem)
		{
			std::cerr << "PhotoDrop::reorderPhotos() missing litem";
			std::cerr << std::endl;
			continue;
		}

		PhotoItem *item = dynamic_cast<PhotoItem *>(litem->widget());
		if (item)
		{
			
			int selectedRow;
			int selectedColumn;
			int rowSpan;
			int colSpan;
			glayout->getItemPosition(i, &selectedRow, &selectedColumn, &rowSpan, &colSpan);

			std::cerr << "PhotoDrop::reorderPhotos() item: " << item;
			std::cerr << " layoutIdx: " << i;
			std::cerr << " item pos(" << selectedRow << ", " << selectedColumn;
			std::cerr << ")" << std::endl;
			
			gridIndex idx(selectedRow, selectedColumn);
			photoItems[idx] = item;
	
		}
		else
		{
			std::cerr << "PhotoDrop::reorderPhotos() Found Child, which is not a PhotoItem???";
			std::cerr << std::endl;
		}
	}

	pit = photoItems.begin(); 
	if (pit == photoItems.end())
	{
		std::cerr << "PhotoDrop::reorderPhotos() No PhotoItems.";
		std::cerr << std::endl;

		mColumns = 1;

		// no PhotoItems here.
		return;
	}

	int minWidth = (pit->second)->minimumWidth();

#define EXPECTED_WIDTH 	(200)
	if (minWidth < EXPECTED_WIDTH)
	{
		minWidth = EXPECTED_WIDTH;
	}
	int space = width();
	mColumns = space / minWidth;
	// incase its too thin!
	if (mColumns < 1)
	{
		mColumns = 1;
	}

	std::cerr << "PhotoDrop::reorderPhotos() minWidth: " << minWidth << " space: " << space;
	std::cerr << " columns: " << mColumns;
	std::cerr << std::endl;

	std::cerr << "PhotoDrop::reorderPhotos() Getting ordered Items from Layout";
	std::cerr << std::endl;


	for(pit = photoItems.begin(); pit != photoItems.end(); pit++)
	{
		glayout->removeWidget(pit->second);
	}
	
	for(pit = photoItems.begin(), i = 0; pit != photoItems.end(); pit++, i++)
	{
		int row = i / mColumns;
		int column = i % mColumns;

		std::cerr << "Inserting item: " << pit->second << " at (" << row << "," << column << ")";
		std::cerr << std::endl;
		glayout->addWidget(pit->second, row, column, Qt::AlignCenter);
	}
}
void CellMLAnnotationViewMetadataEditDetailsWidget::updateGui(const Items &pItems,
                                                              const QString &pErrorMsg,
                                                              const bool &pLookupTerm,
                                                              const int &pItemsVerticalScrollBarPosition,
                                                              const bool &pRetranslate)
{
    // Note: we are using certain layouts to dislay the contents of our view,
    //       but this unfortunately results in some very bad flickering on OS X.
    //       This can, however, be addressed using a stacked widget, so...

    // Prevent ourselves from being updated (to avoid any flickering)

    setUpdatesEnabled(false);

    // Create a widget which will contain our GUI

    QWidget *newMainWidget = new QWidget(this);
    QVBoxLayout *newMainLayout = new QVBoxLayout(newMainWidget);

    newMainLayout->setMargin(0);

    newMainWidget->setLayout(newMainLayout);

    // Create a form widget which will contain our qualifier and term fields

    QWidget *newFormWidget = new QWidget(newMainWidget);
    QFormLayout *newFormLayout = new QFormLayout(newFormWidget);

    newFormWidget->setLayout(newFormLayout);

    // Add our qualifier field

    // Create a widget which will contain both our qualifier value widget and a
    // button to look up the qualifier

    QWidget *qualifierWidget = new QWidget(newFormWidget);

    QHBoxLayout *qualifierWidgetLayout = new QHBoxLayout(qualifierWidget);

    qualifierWidgetLayout->setMargin(0);

    qualifierWidget->setLayout(qualifierWidgetLayout);

    // Create our qualifier value widget

    mQualifierValue = new QComboBox(qualifierWidget);

    mQualifierValue->addItems(CellMLSupport::CellMLFileRdfTriple::qualifiersAsStringList());

    mQualifierValue->setCurrentIndex(mQualifierIndex);

    connect(mQualifierValue, SIGNAL(currentIndexChanged(int)),
            this, SLOT(qualifierChanged(const int &)));
    connect(mQualifierValue, SIGNAL(currentIndexChanged(const QString &)),
            this, SLOT(qualifierChanged(const QString &)));

    // Create our qualifier lookup button widget

    mLookupQualifierButton = new QPushButton(qualifierWidget);
    // Note #1: ideally, we could assign a QAction to our QPushButton, but this
    //          cannot be done, so... we assign a few properties by hand...
    // Note #2: to use a QToolButton would allow us to assign a QAction to it,
    //          but a QToolButton doesn't look quite the same as a QPushButton
    //          on some platforms, so...

    mLookupQualifierButton->setCheckable(true);
    mLookupQualifierButton->setChecked(mLookupQualifierButtonIsChecked);
    mLookupQualifierButton->setIcon(QIcon(":/oxygen/categories/applications-internet.png"));
    mLookupQualifierButton->setStatusTip(tr("Look up the qualifier"));
    mLookupQualifierButton->setToolTip(tr("Look Up"));
    mLookupQualifierButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    connect(mLookupQualifierButton, SIGNAL(clicked()),
            this, SLOT(lookupQualifier()));

    // Add our QComboBox and QPushButton to our cmeta:id widget

    qualifierWidgetLayout->addWidget(mQualifierValue);
    qualifierWidgetLayout->addWidget(mLookupQualifierButton);

    // Add our qualifier widget to our main layout

    newFormLayout->addRow(Core::newLabel(tr("Qualifier:"), 1.0, true, newFormWidget),
                          qualifierWidget);

    // Add our term field

    // Create a widget which will contain both our qualifier value widget and a
    // button to look up the qualifier

    QWidget *termWidget = new QWidget(newFormWidget);

    QHBoxLayout *termWidgetLayout = new QHBoxLayout(termWidget);

    termWidgetLayout->setMargin(0);

    termWidget->setLayout(termWidgetLayout);

    // Create our term value widget

    mTermValue = new QLineEdit(termWidget);

    mTermValue->setText(mTerm);
    // Note: we set the text to whatever term was previously being looked up and
    //       this before tracking changes to the term since we don't want to
    //       trigger a call to termChanged(). Indeed, we might come here as a
    //       result of a retranslation so we shouldn't look up for the term and,
    //       instead, we should call updateItemsGui() which we do at the end of
    //       this procedure...

    connect(mTermValue, SIGNAL(textChanged(const QString &)),
            this, SLOT(termChanged(const QString &)));

    // Create our add term button widget

    mAddTermButton = new QPushButton(termWidget);

    mAddTermButton->setEnabled(false);
    mAddTermButton->setIcon(QIcon(":/oxygen/actions/list-add.png"));
    mAddTermButton->setStatusTip(tr("Add the term"));
    mAddTermButton->setToolTip(tr("Add"));
    mAddTermButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    connect(mAddTermButton, SIGNAL(clicked()),
            this, SLOT(addTerm()));

    // Add our QComboBox and QPushButton to our cmeta:id widget

    termWidgetLayout->addWidget(mTermValue);
    termWidgetLayout->addWidget(mAddTermButton);

    // Add our term widget to our main layout

    newFormLayout->addRow(Core::newLabel(tr("Term:"), 1.0, true, newFormWidget),
                          termWidget);

    // Reset the tab order from our parent's CellML list's tree view widget
    // Note: ideally, we would take advantage of Qt's signal/slot approach with
    //       the signal being emitted here and the slot being implemented in
    //       mParent, but this wouldn't work here since updateGui() gets called
    //       as part of the creation of this metadata details widget, so...

    setTabOrder(qobject_cast<QWidget *>(mParent->cellmlList()->treeViewWidget()),
                mQualifierValue);
    setTabOrder(mQualifierValue, mLookupQualifierButton);
    setTabOrder(mLookupQualifierButton, mTermValue);
    setTabOrder(mTermValue, mAddTermButton);

    // Create a stacked widget (within a scroll area, so that only the items get
    // scrolled, not the whole metadata edit details widget) which will contain
    // a grid with the results of our terms lookup

    QScrollArea *newItemsScrollArea = new QScrollArea(newMainWidget);

    newItemsScrollArea->setFrameShape(QFrame::NoFrame);
    newItemsScrollArea->setWidgetResizable(true);

    // Add our 'internal' widgets to our new main widget

    newMainLayout->addWidget(newFormWidget);
    newMainLayout->addWidget(new Core::BorderedWidget(newItemsScrollArea,
                                                      true, false, false, false));

    // Keep track of the position of our items vertical scroll bar
    // Note: this is required to make sure that the position doesn't get reset
    //       as a result of retranslating the GUI...

    connect(newItemsScrollArea->verticalScrollBar(), SIGNAL(sliderMoved(int)),
            this, SLOT(trackItemsVerticalScrollBarPosition(const int &)));

    // Add our new widget to our stacked widget

    mWidget->addWidget(newMainWidget);

    // Remove the contents of our old form layout

    if (mFormWidget)
        for (int i = 0, iMax = mFormLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mFormLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

    // Reset the widget of our old items scroll area and stop tracking the
    // position of its vertical scroll bar
    // Note: the resetting this will automatically delete our old grid widget...

    if (mItemsScrollArea) {
        mItemsScrollArea->setWidget(0);

        disconnect(mItemsScrollArea->verticalScrollBar(), SIGNAL(sliderMoved(int)),
                   this, SLOT(trackItemsVerticalScrollBarPosition(const int &)));
    }

    // Get rid of our old main widget and layout (and its contents)

    if (mMainWidget) {
        mWidget->removeWidget(mMainWidget);

        for (int i = 0, iMax = mMainLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mMainLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

        delete mMainWidget;
    }

    // Keep track of our new main widgets and layouts

    mMainWidget = newMainWidget;
    mMainLayout = newMainLayout;

    mFormWidget = newFormWidget;
    mFormLayout = newFormLayout;

    mItemsScrollArea = newItemsScrollArea;

    mGridWidget = 0;   // Note: this will be set by our
    mGridLayout = 0;   //       other updateGui() function...

    // Allow ourselves to be updated again

    setUpdatesEnabled(true);

    // Update our items GUI

    updateItemsGui(pItems, pErrorMsg, pLookupTerm);

    // Request for something to be looked up, if needed

    if (mLookupInformation)
        // Look up an 'old' qualifier, resource or resource id

        genericLookup(mInformation, mType, pRetranslate);

    // Set the position of our vertical scroll bar

    mItemsScrollArea->verticalScrollBar()->setValue(pItemsVerticalScrollBarPosition);
}
Exemple #23
0
void PhotoDrop::moveRight()
{
	std::cerr << "PhotoDrop::moveRight()";
	std::cerr << std::endl;

	QLayout *alayout = layout();
	if (!alayout)
	{
		std::cerr << "PhotoDrop::moveRight() No Layout";
		std::cerr << std::endl;
		return;
	}

	QGridLayout *glayout = dynamic_cast<QGridLayout *>(alayout);
	if (!glayout)
	{
		std::cerr << "PhotoDrop::moveRight() not GridLayout... not much we can do!";
		std::cerr << std::endl;
		return;
	}
	
	int count = alayout->count();
	if ((!mSelected) || (count < 2))
	{
		std::cerr << "PhotoDrop::moveRight() Not enough items";
		std::cerr << std::endl;
		return;
	}

	int index = alayout->indexOf(mSelected);
	int selectedRow;
	int selectedColumn;
	int rowSpan;
	int colSpan;
	glayout->getItemPosition(index, &selectedRow, &selectedColumn, &rowSpan, &colSpan);

	int maxRow = (count - 1) / mColumns;
	int maxCol = (count - 1) % mColumns;
	if ((selectedRow == maxRow) && (selectedColumn == maxCol))
	{
		std::cerr << "PhotoDrop::moveRight() Selected is last item";
		std::cerr << std::endl;
		return;
	}

	int swapRow = selectedRow;
	int swapColumn = selectedColumn + 1;

	if (swapColumn == mColumns)
	{
		swapRow++;
		swapColumn = 0;
	}

	std::cerr << "PhotoDrop::moveRight() Trying to swap (" << selectedRow << ",";
	std::cerr << selectedColumn << ") <-> (" << swapRow;
	std::cerr << "," << swapColumn << ")";
	std::cerr << std::endl;

	QLayoutItem *litem = glayout->itemAtPosition(swapRow, swapColumn);
	if (!litem)
	{
		std::cerr << "PhotoDrop::moveRight() No layout item to the right";
		std::cerr << std::endl;
		return;
	}

	QWidget *widget = litem->widget();

	if (!widget)
	{
		std::cerr << "PhotoDrop::moveRight() No item to the right";
		std::cerr << std::endl;
		return;
	}

	/* grab both items, and switch */
	std::cerr << "PhotoDrop::moveRight() could move index: " << index;
	std::cerr << std::endl;

	glayout->removeWidget(widget);
	glayout->removeWidget(mSelected);

	glayout->addWidget(widget, selectedRow, selectedColumn, Qt::AlignCenter);
	glayout->addWidget(mSelected, swapRow, swapColumn, Qt::AlignCenter);

	checkMoveButtons();
}
Exemple #24
0
void FriendListWidget::setMode(Mode mode)
{
    if (this->mode == mode)
        return;

    this->mode = mode;

    if (mode == Name) {
        circleLayout = new GenericChatItemLayout;
        circleLayout->getLayout()->setSpacing(0);
        circleLayout->getLayout()->setMargin(0);

        for (int i = 0; i < Settings::getInstance().getCircleCount(); ++i) {
            addCircleWidget(i);
            CircleWidget::getFromID(i)->setVisible(false);
        }

        // Only display circles once all created to avoid artifacts.
        for (int i = 0; i < Settings::getInstance().getCircleCount(); ++i)
            CircleWidget::getFromID(i)->setVisible(true);

        int count = activityLayout ? activityLayout->count() : 0;
        for (int i = 0; i < count; i++) {
            QWidget* widget = activityLayout->itemAt(i)->widget();
            CategoryWidget* categoryWidget = qobject_cast<CategoryWidget*>(widget);
            if (categoryWidget) {
                categoryWidget->moveFriendWidgets(this);
            } else {
                qWarning() << "Unexpected widget";
            }
        }

        listLayout->addLayout(listLayout->getLayoutOnline());
        listLayout->addLayout(listLayout->getLayoutOffline());
        listLayout->addLayout(circleLayout->getLayout());
        onGroupchatPositionChanged(groupsOnTop);

        if (activityLayout != nullptr) {
            QLayoutItem* item;
            while ((item = activityLayout->takeAt(0)) != nullptr) {
                delete item->widget();
                delete item;
            }
            delete activityLayout;
            activityLayout = nullptr;
        }

        reDraw();
    } else if (mode == Activity) {
        QLocale ql(Settings::getInstance().getTranslation());
        QDate today = QDate::currentDate();
#define COMMENT "Category for sorting friends by activity"
        // clang-format off
        const QMap<Time, QString> names {
            { Time::Today,     tr("Today",                      COMMENT) },
            { Time::Yesterday, tr("Yesterday",                  COMMENT) },
            { Time::ThisWeek,  tr("Last 7 days",                COMMENT) },
            { Time::ThisMonth, tr("This month",                 COMMENT) },
            { Time::LongAgo,   tr("Older than 6 Months",        COMMENT) },
            { Time::Never,     tr("Never",                      COMMENT) },
            { Time::Month1Ago, ql.monthName(today.addMonths(-1).month()) },
            { Time::Month2Ago, ql.monthName(today.addMonths(-2).month()) },
            { Time::Month3Ago, ql.monthName(today.addMonths(-3).month()) },
            { Time::Month4Ago, ql.monthName(today.addMonths(-4).month()) },
            { Time::Month5Ago, ql.monthName(today.addMonths(-5).month()) },
        };
// clang-format on
#undef COMMENT

        activityLayout = new QVBoxLayout();
        bool compact = Settings::getInstance().getCompactLayout();
        for (Time t : names.keys()) {
            CategoryWidget* category = new CategoryWidget(compact, this);
            category->setName(names[t]);
            activityLayout->addWidget(category);
        }

        moveFriends(listLayout->getLayoutOffline());
        moveFriends(listLayout->getLayoutOnline());
        moveFriends(circleLayout->getLayout());

        for (int i = 0; i < activityLayout->count(); ++i) {
            QWidget* widget = activityLayout->itemAt(i)->widget();
            CategoryWidget* categoryWidget = qobject_cast<CategoryWidget*>(widget);
            categoryWidget->setVisible(categoryWidget->hasChatrooms());
        }

        listLayout->removeItem(listLayout->getLayoutOnline());
        listLayout->removeItem(listLayout->getLayoutOffline());

        if (circleLayout != nullptr) {
            listLayout->removeItem(circleLayout->getLayout());

            QLayoutItem* item;
            while ((item = circleLayout->getLayout()->takeAt(0)) != nullptr) {
                delete item->widget();
                delete item;
            }
            delete circleLayout;
            circleLayout = nullptr;
        }

        listLayout->insertLayout(1, activityLayout);

        reDraw();
    }
}
Exemple #25
0
void QLayoutItemProto::setGeometry(const QRect &r)
{
  QLayoutItem *item = qscriptvalue_cast<QLayoutItem*>(thisObject());
  if (item)
    item->setGeometry(r);
}