format * mk_compose(ast_manager & m, unsigned num_children, format * const * children) { return fm(m).mk_app(fid(m), OP_COMPOSE, num_children, (expr * const *) children); }
MainWidget::MainWidget(QWidget *parent,const char *name) :QWidget(parent,name) { login_user_width=160; QString str; QString sql; RDSqlQuery *q; // // HACK: Disable the Broken Custom SuSE Dialogs // setenv("QT_NO_KDE_INTEGRATION","1",1); // // Read Command Options // RDCmdSwitch *cmd=new RDCmdSwitch(qApp->argc(),qApp->argv(),"rdlogin","\n"); delete cmd; // // Fix the Window Size // setMinimumWidth(sizeHint().width()); setMinimumHeight(sizeHint().height()); setMaximumHeight(sizeHint().height()); // // Generate Fonts // QFont default_font("Helvetica",12,QFont::Normal); default_font.setPixelSize(12); qApp->setFont(default_font); QFont button_font=QFont("Helvetica",12,QFont::Bold); button_font.setPixelSize(12); QFont label_font=QFont("Helvetica",16,QFont::Bold); label_font.setPixelSize(12); QFont small_label_font=QFont("Helvetica",12,QFont::Bold); small_label_font.setPixelSize(12); QFont line_edit_font=QFont("Helvetica",12,QFont::Normal); line_edit_font.setPixelSize(12); // // Create And Set Icon // login_rivendell_map=new QPixmap(rivendell_xpm); setIcon(*login_rivendell_map); // // Text Validator // RDTextValidator *validator=new RDTextValidator(this,"validator"); // // Ensure that the system daemons are running // RDInitializeDaemons(); // // Load Configs // login_config=new RDConfig(); login_config->load(); str=QString(tr("RDLogin - Station:")); setCaption(QString().sprintf("%s %s",(const char *)str, (const char *)login_config->stationName())); // // Open Database // QString err(tr("rdlogin : "******"Can't Connect"),err); exit(0); } // // RIPC Connection // login_ripc=new RDRipc(login_config->stationName()); connect(login_ripc,SIGNAL(connected(bool)),this,SLOT(connectedData(bool))); connect(login_ripc,SIGNAL(userChanged()),this,SLOT(userData())); login_ripc->connectHost("localhost",RIPCD_TCP_PORT, login_config->password()); // // Station // login_station=new RDStation(login_config->stationName()); // // User Label // login_label=new QLabel(this,"login_label"); login_label->setFont(label_font); login_label->setAlignment(AlignCenter); login_label->setText(tr("Current User: unknown")); // // User Name // login_username_box=new QComboBox(this,"login_username_box"); login_username_box->setFont(line_edit_font); login_username_box->setFocus(); QFontMetrics fm(line_edit_font); sql="select LOGIN_NAME from USERS where ADMIN_CONFIG_PRIV=\"N\"\ order by LOGIN_NAME"; q=new RDSqlQuery(sql); while(q->next()) { login_username_box->insertItem(q->value(0).toString()); if(fm.width(q->value(0).toString())>login_user_width) { login_user_width=fm.width(q->value(0).toString()); } } delete q; if(login_user_width>900) { login_user_width=900; } login_username_label=new QLabel(login_username_box,tr("&Username:"******"login_username_label"); login_username_label->setFont(small_label_font); login_username_label->setAlignment(AlignRight|AlignVCenter|ShowPrefix); // // Password // login_password_edit=new QLineEdit(this,"login_password_edit"); login_password_edit->setFont(line_edit_font); login_password_edit->setMaxLength(16); login_password_edit->setValidator(validator); login_password_edit->setEchoMode(QLineEdit::Password); login_password_label=new QLabel(login_password_edit,tr("&Password:"******"login_password_label"); login_password_label->setFont(small_label_font); login_password_label->setAlignment(AlignRight|AlignVCenter|ShowPrefix); connect(login_password_edit,SIGNAL(returnPressed()),this,SLOT(loginData())); // // Login Button // login_button=new QPushButton(this,"login_button"); login_button->setFont(button_font); login_button->setText(tr("&Set User")); connect(login_button,SIGNAL(clicked()),this,SLOT(loginData())); // // Logout Button // logout_button=new QPushButton(this,"logout_button"); logout_button->setFont(button_font); logout_button->setText(tr("&Default\nUser")); connect(logout_button,SIGNAL(clicked()),this,SLOT(logoutData())); // // Cancel Button // cancel_button=new QPushButton(this,"cancel_button"); cancel_button->setFont(button_font); cancel_button->setText(tr("&Cancel")); connect(cancel_button,SIGNAL(clicked()),this,SLOT(cancelData())); resizeEvent(NULL); }
QRect StyleHelper::drawText(QPainter* p, const QRect& rc, QString& str, int nLines, int nFlags, const QColor& color, const QFont& font, bool bElided) { if (str.isEmpty()) { qDebug() << "[WARNING]: the text should not be empty when drawing!"; return QRect(); } QFontMetrics fm(font); if (rc.height() < (fm.height() + fm.leading()) * nLines) { qDebug() << "[WARNING]: space is not enough for drawing! text: " << str.left(30) << "..."; } //if (rc.width() * nLines < fm.width(str)) { // qDebug() << "[WARNING]: width should bigger than font metrics when drawing! text:" << str.left(30) << "..."; //} p->save(); p->setPen(color); p->setFont(font); int nWidth = 0; int nHeight = 0; int nHeightLine = p->fontMetrics().height() + leading(); QRect rcRet(rc.x(), rc.y(), rc.width(), nHeightLine); rcRet.adjust(margin(), 0, -margin(), 0); QTextLayout textLayout(str, p->font()); QTextOption opt = textLayout.textOption(); opt.setWrapMode(QTextOption::WrapAnywhere); textLayout.setTextOption(opt); textLayout.beginLayout(); while (nLines) { QTextLine line = textLayout.createLine(); if (!line.isValid()) { break; } line.setLineWidth(rcRet.width()); QString lineText; if (nLines == 1 && bElided) { // the last line lineText = p->fontMetrics().elidedText(str, Qt::ElideRight, rcRet.width()); nWidth = qMax<int>(p->fontMetrics().width(lineText), nWidth); } else { lineText = str.left(line.textLength()); nWidth = qMax<int>(p->fontMetrics().width(lineText), nWidth); } str.remove(0, line.textLength()); p->drawText(rcRet, nFlags, lineText); nHeight += nHeightLine; rcRet.setRect(rc.x(), rc.y() + nHeight, nWidth, nHeightLine); rcRet.adjust(margin(), 0, -margin(), 0); nLines--; } textLayout.endLayout(); rcRet.setRect(rc.x() + margin(), rc.y(), nWidth + margin(), nHeight); //rcRet.adjust(margin(), 0, -margin(), 0); p->restore(); return rcRet; }
QTXLSX_USE_NAMESPACE void MainWindow::exportAsXLSXA(QString fileName,WorkSheet *ws) { QString str; QStringList headerArray; //headerArray << "A"<<"B"<<"C"<<"D"<<"E"<<"F"<<"G"<<"H"<<"I"<<"J"<<"K"<<"L"<<"M"<<"N"<<"O"<<"P"<<"Q"<<"R"<<"S"<<"T"<<"U"<<"V"<<"W"<<"X"<<"Y"<<"Z"<<"AA"<<"AB"<<"AC"<<"AD"<<"AE"<<"AF"<<"AG"<<"AH"<<"AI"<<"AJ"<<"AK"<<"AL"<<"AM"<<"AN"<<"AO"<<"AP"<<"AQ"<<"AR"<<"AS"<<"AT"<<"AU"<<"AV"<<"AW"<<"AX"<<"AY"<<"AZ"; bool bstatus; int i,j; int linecount = 0; QStandardItem *item; QModelIndex index; const ProxyFilter *proxyFilter = 0; const WorkSheetModel *model = 0; if (!ws || !ws->fixTable) { qWarning() << "ws is null or HAS NO FIX TABLE" << __FILE__ << __LINE__; GUI::ConsoleMessage msg("Export failed, work sheet is null or has no table", GUI::ConsoleMessage::ErrorMsg); displayConsoleMessage(msg); return; } model = ws->fixTable->getWorkSheetModel(); QFileInfo fi(fileName); if (fi.suffix().toLower() != "xlsx") fileName.append(".xlsx"); Document xlsx; QString xmlFileName = ws->getFileName(); xlsx.addSheet("From:" + xmlFileName); Format headerStyle; headerStyle.setFontBold(true); headerStyle.setHorizontalAlignment(Format::AlignHCenter); headerStyle.setVerticalAlignment(Format::AlignVCenter); int w; QFontMetrics fm(ws->fixTable->font()); xlsx.setColumnWidth(1,model->columnCount() + 1,20); bool proxyInUse = ws->fixTable->proxyFilterInUse(); for (i=0;i<model->columnCount();i++) { item = model->horizontalHeaderItem(i); xlsx.setColumnFormat(1,i,headerStyle); xlsx.write(1, i+1, item->text()); } if (proxyInUse) { proxyFilter = ws->fixTable->getProxyFilter(); for (i=0;i<proxyFilter->rowCount(); i++ ) { QStringList itemList; for(j=0;j< proxyFilter->columnCount();j++) { index = proxyFilter->index(i,j); index = proxyFilter->mapToSource(index); item = model->itemFromIndex(index); if (item) { xlsx.write(i+2,j+1,item->text()); } } } } else { for(i=0;i<model->rowCount();i++) { for(j=0;j< model->columnCount();j++) { index = model->index(i,j); item = model->itemFromIndex(index); if (item) { xlsx.write(i+2,j+1,item->text()); } } } } xlsx.saveAs(fileName); GUI::ConsoleMessage msg(QString("Exported to " + fileName + ", " + QString::number(i) + " lines.")); displayConsoleMessage(msg); }
void TEWidget::paintEvent( QPaintEvent* pe ) { //{ static int cnt = 0; printf("paint %d\n",cnt++); } const QPixmap* pm = backgroundPixmap(); QPainter paint; setUpdatesEnabled(FALSE); paint.begin( this ); paint.setBackgroundMode( TransparentMode ); HCNT("paintEvent"); qDebug("in TEWidget::paintEvent()"); //sleep(2); // Note that the actual widget size can be slightly larger // than the image (the size is truncated towards the smaller // number of characters in `resizeEvent'. The paint rectangle // can thus be larger than the image, but less then the size // of one character. QRect rect = pe->rect().intersect(contentsRect()); QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int lux = min(columns-1, max(0,(rect.left() - tLx - blX ) / font_w)); int luy = min(lines-1, max(0,(rect.top() - tLy - bY ) / font_h)); int rlx = min(columns-1, max(0,(rect.right() - tLx - blX ) / font_w)); int rly = min(lines-1, max(0,(rect.bottom() - tLy - bY ) / font_h)); /* printf("paintEvent: %d..%d, %d..%d (%d..%d, %d..%d)\n",lux,rlx,luy,rly, rect.left(), rect.right(), rect.top(), rect.bottom()); */ // if (pm != NULL && color_table[image->b].transparent) // erase(rect); // BL: I have no idea why we need this, and it breaks the refresh. QChar *disstrU = new QChar[columns]; QFontMetrics fm(font()); for (int y = luy; y <= rly; y++) { int draw_font_w=0; for (int x = lux; x <= rlx; x++) { int len = 1; disstrU[0] = fontMap(image[loc(x,y)].c); int cf = image[loc(x,y)].f; int cb = image[loc(x,y)].b; int cr = image[loc(x,y)].r; while (x+len <= rlx && image[loc(x+len,y)].f == cf && image[loc(x+len,y)].b == cb && image[loc(x+len,y)].r == cr ) { disstrU[len] = fontMap(image[loc(x+len,y)].c); len += 1; } QString unistr(disstrU,len); /* qDebug("blX+tLx+font_w*x: %d", blX+tLx+font_w*x); qDebug("bY+tLy+font_h*y: %d", bY+tLy+font_h*y); qDebug("font_w*len: %d", font_w*len); qDebug("font_h: %d", font_h); qDebug("font_w: %d", font_w); qDebug("x: %d", x); */ //drawAttrStr(paint, QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), unistr, image[loc(x,y)], pm != NULL, false); drawAttrStr(paint, QRect(blX+tLx+draw_font_w,bY+tLy+font_h*y,font_w*len/2,font_h), unistr, image[loc(x,y)], pm != NULL, false); draw_font_w+=fm.width(unistr); //sleep(2); x += len - 1; } } delete [] disstrU; drawFrame( &paint ); paint.end(); setUpdatesEnabled(TRUE); }
int WiresharkApplication::monospaceTextSize(const char *str) { QFontMetrics fm(mono_font_); return fm.width(str); }
SourceView::SourceView(QWidget *parent,QFont & efont,bool line, QList<QColor> edcolors, QList<QColor> hicolors ) : QWidget(parent) { splitter=new MiniSplitter(this); splitter->setOrientation(Qt::Vertical); QFrame *framebis=new QFrame(splitter); framebis->setLineWidth(0); framebis->setFrameShape(QFrame::NoFrame); framebis->setFrameShadow(QFrame::Plain); framebis->setFrameStyle(QFrame::NoFrame); QVBoxLayout* mainlay = new QVBoxLayout(framebis ); mainlay->setSpacing(0); mainlay->setMargin(0); centralToolBar=new QToolBar("ToolBar",framebis); centralToolBar->setFloatable(false); centralToolBar->setOrientation(Qt::Horizontal); centralToolBar->setMovable(false); centralToolBar->setIconSize(QSize(16,16 )); centralToolBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); mainlay->addWidget(centralToolBar); QAction *Act = new QAction(getIcon(":/images/fileopen16.png"), tr("Open"), this); connect(Act, SIGNAL(triggered()), this, SLOT(fileOpen())); centralToolBar->addAction(Act); centralToolBar->addSeparator(); titleLabel=new QLabel("(read only)",centralToolBar); centralToolBar->addWidget(titleLabel); QFrame *frame=new QFrame(framebis); frame->setLineWidth(0); frame->setFrameShape(QFrame::NoFrame); frame->setFrameShadow(QFrame::Plain); frame->setFrameStyle(QFrame::NoFrame); mainlay->addWidget(frame); lastdocument=""; editor=new LightLatexEditor(frame,efont,edcolors,hicolors,""); connect(editor, SIGNAL(requestFind()), this, SLOT(showFind())); connect(editor, SIGNAL(requestGotoLine()), this, SLOT(showGoto())); m_lineNumberWidget = new LightLineNumberWidget( editor, frame); m_lineNumberWidget->setFont(efont); QFontMetrics fm( efont ); m_lineNumberWidget->setFixedWidth( fm.width( "00000" ) + 22 ); QHBoxLayout* lay = new QHBoxLayout( frame ); lay->setSpacing(0); lay->setMargin(0); lay->addWidget( m_lineNumberWidget ); lay->addWidget( editor ); setFocusProxy( editor ); setLineNumberWidgetVisible(line); Stack=new QStackedWidget(this); Stack->setLineWidth(0); Stack->setFrameShape(QFrame::NoFrame); Stack->setFrameShadow(QFrame::Plain); findwidget=new LightFindWidget(Stack); Stack->addWidget(findwidget); findwidget->SetEditor(editor); connect(findwidget, SIGNAL( requestHide() ), Stack, SLOT( hide() ) ); connect(findwidget, SIGNAL( requestExtension() ), this, SLOT( showFind() ) ); gotolinewidget=new LightGotoLineWidget(Stack); Stack->addWidget(gotolinewidget); gotolinewidget->SetEditor(editor); connect(gotolinewidget, SIGNAL( requestHide() ), Stack, SLOT( hide() ) ); Stack->hide(); splitter->addWidget(framebis); splitter->addWidget(Stack); QVBoxLayout *mainlayout= new QVBoxLayout(this); mainlayout->setSpacing(0); mainlayout->setMargin(0); mainlayout->addWidget(splitter); }
void KviTopicWidget::paintColoredText(QPainter * p, QString text, const QPalette & cg, const QRect & rect) { QFontMetrics fm(p->fontMetrics()); bool curBold = false; bool curItalic = false; bool curUnderline = false; unsigned char curFore = KVI_LABEL_DEF_FORE; //default fore unsigned char curBack = KVI_LABEL_DEF_BACK; //default back int baseline = rect.top() + rect.height() - fm.descent() - 1; int curX = rect.x() + 1; // is the margin int maxX = rect.width() - 2; // 2 is 1*margin unsigned int idx = 0; QFont::Style normalFontStyle = p->font().style(); while((idx < (unsigned int)text.length()) && (curX < maxX)) { unsigned short c = text[(int)idx].unicode(); unsigned int start = idx; while((idx < (unsigned int)text.length()) && (c != KviControlCodes::Color) && (c != KviControlCodes::Bold) && (c != KviControlCodes::Italic) && (c != KviControlCodes::Underline) && (c != KviControlCodes::Reverse) && (c != KviControlCodes::Reset) && (c != KviControlCodes::Icon)) { idx++; c = text[(int)idx].unicode(); } int len = idx - start; int wdth; if(len > 0) { QString szText = text.mid(start, len); wdth = fm.width(szText); if(curFore == KVI_LABEL_DEF_FORE) { p->setPen(cg.text().color()); } else { if(curFore > 16) p->setPen(cg.background().color()); else p->setPen(KVI_OPTION_MIRCCOLOR(curFore)); } if(curBack != KVI_LABEL_DEF_BACK) { if(curBack > 16) { p->fillRect(curX, rect.y() + 2, wdth, rect.height() - 4, cg.text()); } else { p->fillRect(curX, rect.y() + 2, wdth, rect.height() - 4, KVI_OPTION_MIRCCOLOR(curBack)); } } QFont newFont = p->font(); newFont.setStyle((curItalic ^ (normalFontStyle != QFont::StyleNormal)) ? QFont::StyleItalic : QFont::StyleNormal); p->setFont(newFont); p->drawText(curX, baseline, szText.left(len)); if(curBold) p->drawText(curX + 1, baseline, szText.left(len)); if(curUnderline) { p->drawLine(curX, baseline + 1, curX + wdth, baseline + 1); } } else { wdth = 0; } curX += wdth; switch(c) { case KviControlCodes::Bold: curBold = !curBold; ++idx; break; case KviControlCodes::Italic: curItalic = !curItalic; ++idx; break; case KviControlCodes::Underline: curUnderline = !curUnderline; ++idx; break; case KviControlCodes::Reverse: { char auxBack = curBack; curBack = curFore; curFore = auxBack; } ++idx; break; case KviControlCodes::Reset: curFore = KVI_LABEL_DEF_FORE; curBack = KVI_LABEL_DEF_BACK; curBold = false; curItalic = false; curUnderline = false; ++idx; break; case KviControlCodes::Color: { ++idx; unsigned char fore; unsigned char back; idx = KviControlCodes::getUnicodeColorBytes(text, idx, &fore, &back); if(fore != KviControlCodes::NoChange) { curFore = fore; if(back != KviControlCodes::NoChange) curBack = back; } else { // only a CTRL+K curBack = KVI_LABEL_DEF_BACK; curFore = KVI_LABEL_DEF_FORE; } } break; case KviControlCodes::Icon: { ++idx; unsigned int icoStart = idx; while((idx < (unsigned int)text.length()) && (text[(int)idx].unicode() > 32)) idx++; KviCString lookupString = text.mid(icoStart, idx - icoStart); KviTextIcon * icon = g_pTextIconManager->lookupTextIcon(lookupString.ptr()); if(icon) { QPixmap * pigzmap = icon->pixmap(); p->drawPixmap(curX, (baseline + 2) - pigzmap->height(), *(pigzmap)); curX += pigzmap->width(); } else { idx = icoStart; } } break; } } }
double FontScalingWidget::calculateFontPointSizeF(const QString& text, const QSize &size) { QFontMetrics fmint = d_widget->fontMetrics(); QFontMetricsF fm(fmint); QFont f = d_widget->font(); QString longestLine; double txtWidth; double txtHeight; int linecnt = text.count("\n") + 1; if(linecnt > 1) { QStringList lines = text.split("\n"); qSort(lines.begin(), lines.end(), FontScalingWidget::longerThan); qslisttoc(lines); longestLine = lines.first(); txtHeight = fm.lineSpacing() * linecnt; } else { longestLine = text; /* no newline */ txtHeight = fm.height(); } double borderH1 = size.height() - d_botTopBorderWidth; double borderH2 = borderH1 - d_botTopBorderWidth; /* scale according to width and height */ if(d_scaleMode == 2) { txtWidth = fm.width(longestLine); double borderW1 = size.width() - d_lateralBorderWidth; double borderW2 = borderW1 - d_lateralBorderWidth; /* first scale according to height (same algorithme as below) and then verify width */ borderH2 = borderH1; if(txtHeight == (borderH1 + 1) || txtHeight == (borderH1)) { //printf("good: text for <%s> :text \"%s\" %.2f\e[0m | borderH1: %.2f borderH2: %.2f pointSizeF %.2f, h: %.2f\n", //widget()->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, borderH1,borderH2, f.pointSizeF(), borderH1 ); } else { while((txtHeight > borderH1) && f.pointSizeF() > MIN_FONT_SIZE) { if(f.pointSizeF() <= 0.0) f.setPointSizeF(1.0); f.setPointSizeF(f.pointSizeF() - 0.5); //printf(" \e[1;36m -- DECREASING font size for object \"%s\" :text \"%s\" height %.1f - point size %.2f - h: %.2f\e[0m\n", // d_widget->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, f.pointSizeF(), borderH1); QFontMetricsF tmpFm(f); txtHeight = linecnt * tmpFm.lineSpacing(); } while(txtHeight < borderH2) { if(f.pointSizeF() <= 0.0) f.setPointSizeF(0.5); f.setPointSizeF(f.pointSizeF() + 0.5); //printf(" \e[1;35m ++ INCREASING font size for object\"%s\" :text \"%s\" height %.1f - point size %.2f - h: %.2f\e[0m\n", // d_widget->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, f.pointSizeF(), borderH2); QFontMetricsF tmpFm(f); txtHeight = linecnt * tmpFm.lineSpacing(); } } // check if width does not go outside QFontMetricsF tmpFm(f); txtWidth = tmpFm.width(longestLine); while((txtWidth > borderW2) && f.pointSizeF() > MIN_FONT_SIZE) { if(f.pointSizeF() <= 0.0) f.setPointSizeF(1.0); f.setPointSizeF(f.pointSizeF() - 0.5); //printf(" \e[1;36m -- next DECREASING font size \"%s\" :text \"%s\" width %.1f height %.1f - point size %.2f - w: %.2f\e[0m\n", // d_widget->objectName().toAscii().constData(), text.toAscii().constData(), txtWidth, txtHeight, f.pointSizeF(), borderW2); QFontMetricsF tmpFm(f); txtWidth = tmpFm.width(longestLine); txtHeight = linecnt * tmpFm.lineSpacing(); } /* scale according to height only */ } else { borderH2 = borderH1; if(txtHeight == (borderH1 + 1) || txtHeight == (borderH1)) { //if(txtHeight == borderH1) { //printf("good: text h %.2f\e[0m | borderH1: %.2f borderH2: %.2f pointSizeF %.2f, h: %.2f\n", // txtHeight, borderH1,borderH2, f.pointSizeF(), borderH1 ); } else { while((txtHeight > borderH1) && f.pointSizeF() > MIN_FONT_SIZE) { if(f.pointSizeF() <= 0.0) f.setPointSizeF(1.0); f.setPointSizeF(f.pointSizeF() - 0.5); //printf(" \e[1;36m -- DECREASING font size \"%s\" :text \"%s\" height %.1f - point size %.2f - h: %.2f\e[0m\n", // widget()->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, f.pointSizeF(), borderH1); QFontMetricsF tmpFm(f); txtHeight = linecnt * tmpFm.lineSpacing(); } while(txtHeight < borderH2) { if(f.pointSizeF() <= 0.0) f.setPointSizeF(0.5); f.setPointSizeF(f.pointSizeF() + 0.5); //printf(" \e[1;35m ++ INCREASING font size \"%s\" :text \"%s\" height %.1f - point size %.2f - h: %.2f\e[0m\n", // widget()->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, f.pointSizeF(), borderH2); QFontMetricsF tmpFm(f); txtHeight = linecnt * tmpFm.lineSpacing(); } } } return f.pointSizeF(); }
void TGLFunWidget::paintScale(void) { QRect rc = rect(); QFont glFont("Courier", 12, QFont::Normal); QFontMetrics fm(glFont); QString val; int num = 8, fontW1 = fm.width("12"), fontW2 = fm.width("1234567890"), fontH = fm.height(), i; Float minU = 0, maxU = 0, v_start, v_stop, v_step, v, cy; if (!(mesh && mesh->getFEType() != NOTYPE) || rc.height() < 9*fontH) return; minU = *min_element((*results)[funIndex].getResults().begin(),(*results)[funIndex].getResults().end());; maxU = *max_element((*results)[funIndex].getResults().begin(),(*results)[funIndex].getResults().end());; v_start = maxU; v_stop = minU; v_step = (maxU - minU)/(num - 1); cy = rc.top() + 20; v = v_start; if (minU == maxU) { i = getColorIndex(v); glColor3f(colorTable[i].red(),colorTable[i].green(),colorTable[i].blue()); glFont.setStyleStrategy(QFont::OpenGLCompatible); renderText(rc.width() - fontW1 - fontW2 - 10,cy,"█",glFont); glColor3f(1.0 - float(params.bkgColor.red())/255.0,1.0 - float(params.bkgColor.green())/255.0,1.0 - float(params.bkgColor.blue())/255.0); // renderText(rc.width() - fontW2 - 10,cy,QString("%1").arg(v,5,'e',3),glFont); renderText(rc.width() - fontW2 - 10,cy,val.sprintf("%+5.3E",colorTable[i].value()),glFont); return; } for (int k = 0; k < 8; k++) { if (k == 7) v = v_stop; i = getColorIndex(v); glColor3f(colorTable[i].red(),colorTable[i].green(),colorTable[i].blue()); glFont.setStyleStrategy(QFont::OpenGLCompatible); renderText(rc.width() - fontW1 - fontW2 - 10,cy,"█",glFont); glColor3f(1.0 - float(params.bkgColor.red())/255.0,1.0 - float(params.bkgColor.green())/255.0,1.0 - float(params.bkgColor.blue())/255.0); // glColor3f(0,0,0); renderText(rc.width() - fontW2 - 10,cy,val.sprintf("%+5.3E",v),glFont); cy += fontH; v -= v_step; } }
void Game::paintEvent(QPaintEvent *event) { if(gameStarted) { ///*** Setup Painter ***/// QPainter painter(this); QBrush normal(painter.brush()); QBrush manaBar(Qt::blue,Qt::SolidPattern); QBrush healthBar(Qt::green,Qt::SolidPattern); ///*** Prevent painter from drawing if the game is over ***/// if (gameOver) { painter.end(); QPainter painter(this); QFont font("Courier", 15, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width("Game Over!"); int textWidth2 = fm.width("Press ESC to close window"); painter.setFont(font); painter.translate(QPoint(400, 300)); painter.drawText(-textWidth/2, 0, "Game Over!"); painter.drawText(-textWidth2/2, 15, "Press ESC to close window"); killTimer(timerId); std::cout << "BLAHBLAHBLAH\n"; } ///*** Draw Player ***/// if(player->getType() == TANK) { if(player->getCanAttack()) painter.drawImage(player->getLocation().x()-9,player->getLocation().y()-5,player->getAttackFrame()); if(player->getAttacking()) painter.drawImage(player->getLocation().x()-10,player->getLocation().y()-10,player->getManaAttackFrame()); } else if(player->getType() == ASSN) { if(player->getCanAttack()) { painter.drawImage(player->getLocation().x()-20,player->getLocation().y()-17,player->getAttackFrame()); } if(player->bombSet) painter.drawImage(player->bomb->getLocation().x()-20,player->bomb->getLocation().y()-17,player->getManaAttackFrame()); } ///*** Draw Enemies ***/// for(int i=0;i<drones.size();i++) { painter.setBrush(healthBar); painter.drawRect(drones.at(i)->getLocation().x()-15,drones.at(i)->getLocation().y()-20,drones.at(i)->getHealth(), 4); painter.setBrush(normal); painter.drawImage(drones.at(i)->getLocation().x()-15,drones.at(i)->getLocation().y()-15,drones.at(i)->getAttackFrame()); } if(canSpawnArcher) { for(int i=0;i<archers.size();i++) { painter.setBrush(normal); painter.drawImage(archers.at(i)->getLocation().x()-15,archers.at(i)->getLocation().y()-15,archers.at(i)->getAttackFrame()); if(archers.at(i)->getAttacking()) { painter.setBrush(manaBar); painter.drawEllipse(archers.at(i)->bullet->getLocation().x(),archers.at(i)->bullet->getLocation().y(),10,10); } } } ///*** Draw Status Bars ***/// painter.setBrush(healthBar); painter.drawRect(5,5,player->getHealth(),10); painter.setBrush(normal); painter.drawRect(5,5,player->getMaxHealth(),10); painter.setBrush(manaBar); painter.drawRect(5,20,player->getMana(),10); painter.setBrush(normal); painter.drawRect(5,20,player->getMaxMana(),10); ///*** Give player tips at appropriate levels ***/// if (player->getXP() < 1) { if(player->getType() == TANK) { QFont font("Courier", 15, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width("Left Click to 'Enrage', then run into an enemy!"); painter.setFont(font); painter.translate(QPoint(400, 300)); painter.drawText(-textWidth/2, 0, "Left Click to 'Enrage', then run into an enemy!"); } else if(player->getType() == ASSN) { QFont font("Courier", 15, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width("Left Click to Slash enemies, but don't get too close!"); painter.setFont(font); painter.translate(QPoint(400, 300)); painter.drawText(-textWidth/2, 0, "Left Click to Slash enemies, but don't get too close!"); } } if (player->getXP() == 5) { QFont font("Courier", 15, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width("Level Up!\nRight Click for New Skill"); painter.setFont(font); painter.translate(QPoint(400, 300)); painter.drawText(-textWidth/2, 0, "Level Up! Right Click for New Skill"); level=2; emit levelChanged(level); canSpawnArcher = true; } if (player->getXP() == 10) { QFont font("Courier", 15, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width("Level Up!"); painter.setFont(font); painter.translate(QPoint(400, 300)); painter.drawText(-textWidth/2, 0, "Level Up!"); canSpawnArcher = true; level=3; emit levelChanged(level); } } }
format * mk_nil(ast_manager & m) { return fm(m).mk_app(fid(m), OP_NIL); }
format * mk_compose(ast_manager & m, format * f1, format * f2, format * f3, format * f4) { expr * f[4] = { f1, f2, f3, f4 }; return fm(m).mk_app(fid(m), OP_COMPOSE, 4, f); }
format * mk_compose(ast_manager & m, format * f1, format * f2, format * f3) { return fm(m).mk_app(fid(m), OP_COMPOSE, f1, f2, f3); }
NewWindowSchemaPage::NewWindowSchemaPage(Fix8SharedLibList &shareLibs,QWidget *parent) : QWizardPage(parent),fix8SharedLibList(shareLibs) { setTitle("<h1>New Window Wizard</h1>"); setSubTitle("<h2>Select FIX Schema</h2>"); QGridLayout *schemaGrid= new QGridLayout(this); setLayout(schemaGrid); schemaStack = new QStackedLayout(); schemaListView = new QListView(this); schemaListView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); schemaListView->setFlow(QListView::TopToBottom); QFontMetrics fm(schemaListView->font()); int schemaListViewWidth = fm.width("FIX4402")+4; //schemaListView->setMaximumWidth(schemaListViewWidth + 12); schemaListView->setUniformItemSizes(true); connect(schemaListView,SIGNAL(clicked(QModelIndex)),this,SLOT(schemaListViewSlot(QModelIndex))); //schemaListView->setMovement(QListView::Static); //schemaListView->setResizeMode(QListView::Adjust); schemaModel = new QStandardItemModel(this); schemaListView->setModel(schemaModel); selectionModel = schemaListView->selectionModel(); QFont fnt = schemaListView->font(); fnt.setPointSize(fnt.pointSize()+2); fnt.setBold(true); schemaListView->setFont(fnt); noSchemasFoundL = new QLabel(this); QString ss = "QLabel { color: rgb(255,255,255); border-color: rgba(255, 0, 0, 75%); background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #1a3994, stop: 1 #061a33); }"; noSchemasFoundL->setStyleSheet(ss); noSchemasFoundL->setText("No Schemas\nFound"); fnt = noSchemasFoundL->font(); fnt.setBold(true); fnt.setPointSize(fnt.pointSize()+2); noSchemasFoundL->setFont(fnt); noSchemasFoundL->setAlignment(Qt::AlignCenter); schemasListID = schemaStack->addWidget(schemaListView); noSchemasID = schemaStack->addWidget(noSchemasFoundL); schemaStack->setCurrentIndex(noSchemasID); fm = QFontMetrics(schemaListView->font()); schemaListView->setMaximumWidth(fm.averageCharWidth()*24); noSchemasFoundL->setMaximumWidth(fm.averageCharWidth()*24); legend = new QLabel(this); fnt = legend->font(); fnt.setItalic(true); legend->setFont(fnt); #ifdef Q_OS_WIN legend->setText("*System Library"); #else legend->setText("\u002aSystem Library"); #endif infoView = new QQuickView(QUrl("qrc:qml/schemaLocation.qml")); QQmlContext *dc = infoView->rootContext(); /* dc->setContextProperty("backgroundcolor", palette().color(QPalette::Window)); */ QQuickItem *qmlObject = infoView->rootObject(); qmlObject->setProperty("color",palette().color(QPalette::Window)); infoView->setResizeMode(QQuickView::SizeRootObjectToView); infoWidget = QWidget::createWindowContainer(infoView,this); systemDirName = qApp->applicationDirPath() + "/fixschemas"; QVariant returnedValue; qmlObject->setProperty("systemDir",systemDirName); //QMetaObject::invokeMethod (dc, "setSystemDirName", Q_RETURN_ARG(QVariant, returnedValue), // Q_ARG(QVariant,systemDirName)); userDirName = QDir::homePath() + "/f8logview/fixschemas"; schemaGrid->addLayout(schemaStack,0,0); schemaGrid->addWidget(legend,1,0,Qt::AlignLeft); schemaGrid->addWidget(infoWidget,0,1,2,1); schemaGrid->setColumnStretch(0,0); schemaGrid->setColumnStretch(1,1); schemaGrid->setRowStretch(0,1); schemaGrid->setRowStretch(1,0); }
void MeterSlider::paintEvent(QPaintEvent* ev) { int h = height(); int kh = sliderSize().height(); int mh = h - kh; double range = maxValue() - minValue(); int ppos = int(mh * (_value - minValue()) / range); if (_invert) ppos = mh - ppos; QPainter p(this); p.setRenderHint(QPainter::Antialiasing, false); //--------------------------------------------------- // draw meter //--------------------------------------------------- int mw = _meterWidth / _channel; int x = 20; int y1 = kh / 2; int y3 = h - y1; p.setPen(QPen(Qt::white, 2)); for (int i = 0; i < _channel; ++i) { int h = mh - (lrint(fast_log10(meterval[i]) * -20.0f * mh / range)); if (h < 0) h = 0; else if (h > mh) h = mh; p.drawPixmap(x, y1+mh-h, mw, h, onPm, 0, mh-h, mw, h); p.drawPixmap(x, y1, mw, mh-h, offPm, 0, 0, mw, mh-h); //--------------------------------------------------- // draw peak line //--------------------------------------------------- h = mh - (lrint(fast_log10(meterPeak[i]) * -20.0f * mh / range)); if (h > mh) h = mh; if (h > 0) p.drawLine(x, y3-h, x+mw, y3-h); x += mw; } // optimize common case: if (ev->rect() == QRect(20, kh/2, _meterWidth-1, mh)) return; QColor sc(isEnabled() ? _scaleColor : Qt::gray); QColor svc(isEnabled() ? _scaleValueColor : Qt::gray); p.setBrush(svc); //--------------------------------------------------- // draw scale //--------------------------------------------------- int y2 = h - (ppos + y1); p.fillRect(x, y1, _scaleWidth, y2-y1, sc); p.fillRect(x, y2, _scaleWidth, y3-y2, svc); //--------------------------------------------------- // draw tick marks //--------------------------------------------------- QFont f(p.font()); f.setPointSize(6); p.setFont(f); p.setPen(QPen(Qt::darkGray, 2)); QFontMetrics fm(f); int xt = 20 - fm.width("00") - 5; QString s; for (int i = 10; i < 70; i += 10) { h = y1 + lrint(i * mh / range); s.setNum(i - 10); p.drawText(xt, h - 3, s); p.drawLine(15, h, 20, h); } //--------------------------------------------------- // draw slider //--------------------------------------------------- x += _scaleWidth/2; p.setPen(QPen(svc, 0)); p.translate(QPointF(x, y2)); p.setRenderHint(QPainter::Antialiasing, true); p.drawPath(*points); }
virtual void paintEvent(QPaintEvent *ev) { if (tickPosition() == QSlider::NoTicks) return QSlider::paintEvent(ev); QPainter p(this); QStyleOptionSlider option; initStyleOption(&option); const int& ticks( option.tickPosition ); const int available(style()->proxy()->pixelMetric(QStyle::PM_SliderSpaceAvailable, &option, this)); int interval = option.tickInterval; if( interval < 1 ) interval = option.pageStep; if( interval < 1 ) return; const QRect& r(option.rect); const QPalette palette(option.palette); const int fudge(style()->proxy()->pixelMetric(QStyle::PM_SliderLength, &option, this) / 2); int current(option.minimum); int nextLabel = current; QFontMetrics fm(font()); int h = fm.height() + 3; int w = fm.width(QString::number(option.maximum)) + 3; if(available<w) nextLabel = -1; float i = available/(orientation() == Qt::Horizontal ? w : h); float t = option.maximum/interval; int valStep = t/ i + 1; // Since there is no subrect for tickmarks do a translation here. p.save(); p.translate(r.x(), r.y()); p.setPen(palette.color(QPalette::WindowText)); int extra = (option.tickPosition == QSlider::TicksBothSides ? 2 : 1); int tickSize(option.orientation == Qt::Horizontal ? (r.height() - h*extra)/3:(r.width() - w*extra)/3); while(current <= option.maximum) { const int position(QStyle::sliderPositionFromValue(option.minimum, option.maximum, current, available, option.upsideDown) + fudge); // calculate positions if(option.orientation == Qt::Horizontal) { if (ticks & QSlider::TicksAbove) { p.drawLine(position, h, position, tickSize + h); if(current == nextLabel) p.drawText(QRect(position - w/2, 0, w, h), Qt::AlignHCenter, QString::number(current)); } if (ticks & QSlider::TicksBelow) { p.drawLine( position, r.height() - h - tickSize, position, r.height() - h ); if(current == nextLabel) p.drawText(QRect(position - w/2, r.height() - h + 3, w, h), Qt::AlignHCenter, QString::number(current)); } } else { if (ticks & QSlider::TicksAbove) { p.drawLine(w, position, tickSize + w, position); if(current == nextLabel) p.drawText(QRect(0, position - h/2, w - 3, h), Qt::AlignRight | Qt::AlignVCenter, QString::number(current)); } if (ticks & QSlider::TicksBelow) { p.drawLine(r.width() - w - tickSize, position, r.width() - w, position ); if(current == nextLabel) p.drawText(QRect(r.width() - w + 3, position - h/2, w, h), Qt::AlignVCenter, QString::number(current)); } } // go to next position if (current == nextLabel) nextLabel += interval*valStep; current += interval; } p.restore(); option.subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderHandle; style()->proxy()->drawComplexControl(QStyle::CC_Slider, &option, &p, this); }
//----------------------------------------------------------------------------- void resizeColumnsToContents(QTreeWidget* tree, bool includeCollapsedItems) { QList<QTreeWidgetItem*> collapsedItems; // If including collapsed items, first expand the entire tree if (includeCollapsedItems) { for (QTreeWidgetItemIterator iter(tree); *iter; ++iter) { QTreeWidgetItem* item = *iter; if (item->childCount() && !item->isExpanded()) { item->setExpanded(true); collapsedItems.append(item); } } } int i = tree->columnCount(); while (i--) { // Resize to data tree->resizeColumnToContents(i); // Also resize to header, if applicable if (!tree->isHeaderHidden()) { // Get current size int cw = tree->columnWidth(i); // Get header text and icon QString text = tree->headerItem()->text(i); QIcon icon = tree->headerItem()->icon(i); // Get header font, using widget font if unset QFont font = tree->font(); QVariant hfd = tree->headerItem()->data(i, Qt::FontRole); if (hfd.isValid() && hfd.canConvert(QVariant::Font)) { font = hfd.value<QFont>(); } // Calculate size of text and icon QFontMetrics fm(font); int tw = fm.width(text); if (!icon.isNull()) { tw += icon.actualSize(tree->iconSize()).width(); } // Add space for margins and sort indicator tw += 2 * tree->style()->pixelMetric(QStyle::PM_HeaderMargin); tw += 2 * tree->style()->pixelMetric(QStyle::PM_HeaderGripMargin); tw += tree->style()->pixelMetric(QStyle::PM_HeaderMarkSize); // Use header size, if larger if (tw > cw) { tree->setColumnWidth(i, tw); } } } // Restore collapsed state of anything we expanded foreach (QTreeWidgetItem* item, collapsedItems) item->setExpanded(false); }
void FlowCanvas::update(bool updatepos) { if (data) { QFontMetrics fm(the_canvas()->get_font(UmlNormalFont)); FlowCanvas * plabel; FlowCanvas * pstereotype; { ArrowCanvas * aplabel; ArrowCanvas * apstereotype; search_supports(aplabel, apstereotype); plabel = (FlowCanvas *) aplabel; pstereotype = (FlowCanvas *) apstereotype; } // manages relation's stereotype QString s = data->get_short_stereotype(); bool update_label = FALSE; if (s.isEmpty()) { // relation does not have stereotype if (pstereotype != 0) { // removes it the_canvas()->del(pstereotype->stereotype); pstereotype->stereotype = 0; pstereotype = 0; } } else { if (s == "interrupt") s = LabelCanvas::Zigzag; else if (s != LabelCanvas::Zigzag) s = QString("<<") + toUnicode(s) + ">>"; if ((pstereotype == 0) && (begin->type() != UmlArrowPoint)) { // adds relation's stereotype stereotype = new LabelCanvas(s, the_canvas(), 0, 0); update_label = (label != 0); stereotype_default_position(); } else if ((pstereotype != 0) && (pstereotype->stereotype->get_name() != s)) { // update name pstereotype->stereotype->set_name(s); if (auto_pos) pstereotype->stereotype_default_position(); } } // manages relation's name, guard and weight bool horiz = (write_horizontally == UmlDefaultState) ? ((BrowserActivityDiagram *) the_canvas()->browser_diagram()) ->get_write_label_horizontally() : (write_horizontally == UmlYes); used_settings = settings; ((BrowserActivityDiagram *) the_canvas()->browser_diagram()) ->get_activitydrawingsettings(used_settings); s = data->str(horiz, used_settings.drawing_language); QString n = data->get_start()->get_name(); if (! s.isEmpty()) { if (n != "<flow>") s = n + ((horiz) ? ' ' : '\n') + toUnicode(s); else s = toUnicode(s); } else if (n != "<flow>") s = n; if (s.isEmpty()) { if (plabel != 0) { // removes it the_canvas()->del(plabel->label); plabel->label = 0; } } else if ((plabel == 0) && (begin->type() != UmlArrowPoint)) { // adds relation's name label = new LabelCanvas(s, the_canvas(), 0, 0); default_label_position(); } else if ((plabel != 0) && (plabel->label->get_name() != s)) { // update it plabel->label->set_name(s); if (auto_pos || update_label) plabel->default_label_position(); } else if (update_label) plabel->default_label_position(); } if (updatepos) update_pos(); }
/** Overloads default QWidget::paintEvent. Draws the actual * bandwidth graph. */ void RSPermissionMatrixWidget::paintEvent(QPaintEvent *) { //std::cerr << "In paint event!" << std::endl; int S = QFontMetricsF(font()).height(); /* Set current graph dimensions */ _rec = this->frameRect(); /* Start the painter */ _painter->begin(this); /* We want antialiased lines and text */ _painter->setRenderHint(QPainter::Antialiasing); _painter->setRenderHint(QPainter::TextAntialiasing); /* Fill in the background */ _painter->fillRect(_rec, QBrush(BACK_COLOR)); _painter->drawRect(_rec); // draw one line per friend. std::list<RsPeerId> ssllist ; rsPeers->getFriendList(ssllist) ; // sort list { // sort out offline peers if(mHideOffline) { RsPeerDetails peerDetails; for(std::list<RsPeerId>::iterator it = ssllist.begin(); it != ssllist.end();) { rsPeers->getPeerDetails(*it, peerDetails); switch (peerDetails.connectState) { case RS_PEER_CONNECTSTATE_OFFLINE: case RS_PEER_CONNECTSTATE_TRYING_TCP: case RS_PEER_CONNECTSTATE_TRYING_UDP: it = ssllist.erase(it); break; default: it++; break; } } } // sort by name ssllist.sort(sortRsPeerIdByNameLocation); } RsPeerServiceInfo ownServices; rsServiceControl->getOwnServices(ownServices); // Display friend names at the beginning of each column const QFont& font(_painter->font()) ; QFontMetrics fm(font); int peer_name_size = 0 ; float line_height = 2 + fm.height() ; std::vector<QString> names ; for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it) { RsPeerDetails details ; rsPeers->getPeerDetails(*it,details) ; QString name = QString::fromUtf8(details.name.c_str()) + " (" + QString::fromUtf8(details.location.c_str()) + ")"; if(name.length() > 20) name = name.left(20)+"..." ; peer_name_size = std::max(peer_name_size, fm.width(name)) ; names.push_back(name) ; } QPen pen ; pen.setWidth(2) ; pen.setBrush(Qt::black) ; _painter->setPen(pen) ; int i=0; //int x=5/14.0*S ; int y=S*fMATRIX_START_Y ; for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it,++i) { float X = S*fMATRIX_START_X + peer_name_size - fm.width(names[i]) ; float Y = S*fMATRIX_START_Y + (i+0.5)*S*fROW_SIZE + line_height/2.0f-2 ; _painter->drawText(QPointF(X,Y),names[i]) ; if(*it == _current_peer_id) _painter->drawLine(QPointF(X,Y+3),QPointF(X+fm.width(names[i]),Y+3)) ; y += line_height ; } matrix_start_x = S*5/14.0 + S*fMATRIX_START_X + peer_name_size ; // now draw the service names i=0 ; std::vector<int> last_width(10,0) ; for(std::map<uint32_t, RsServiceInfo>::const_iterator it(ownServices.mServiceList.begin());it!=ownServices.mServiceList.end();++it,++i) { QString name = QString::fromUtf8(it->second.mServiceName.c_str()) ; int text_width = fm.width(name) ; int X = matrix_start_x + S*fCOL_SIZE/2 - 2 + i*S*fCOL_SIZE - text_width/2; int height_index = 0 ; while(last_width[height_index] > X-5 && height_index < ((int)last_width.size()-1) ) ++height_index ; int Y = S*fMATRIX_START_Y - S*fICON_SIZE_Y - 2 - line_height * height_index; last_width[height_index] = X + text_width ; // draw a half-transparent rectangle QBrush brush ; brush.setColor(QColor::fromHsvF(0.0f,0.0f,1.0f,0.8f)); brush.setStyle(Qt::SolidPattern) ; QPen pen ; pen.setWidth(2) ; if(_current_service_id == it->second.mServiceType) pen.setBrush(Qt::black) ; else pen.setBrush(Qt::gray) ; _painter->setPen(pen) ; QRect info_pos( X-5,Y-line_height-2, text_width + 10, line_height + 5) ; //_painter->fillRect(info_pos,brush) ; //_painter->drawRect(info_pos) ; _painter->drawLine(QPointF(X,Y+3),QPointF(X+text_width,Y+3)) ; _painter->drawLine(QPointF(X+text_width/2, Y+3), QPointF(X+text_width/2,S*fMATRIX_START_Y+peer_ids.size()*S*fROW_SIZE - S*fROW_SIZE+5)) ; pen.setBrush(Qt::black) ; _painter->setPen(pen) ; _painter->drawText(QPointF(X,Y),name); } // Now draw the global switches. peer_ids.clear() ; for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it) peer_ids.push_back(*it) ; service_ids.clear() ; for(std::map<uint32_t, RsServiceInfo>::const_iterator sit(ownServices.mServiceList.begin());sit!=ownServices.mServiceList.end();++sit) service_ids.push_back(sit->first) ; static const std::string global_switch[2] = { ":/icons/global_switch_off_128.png", ":/icons/global_switch_on_128.png" } ; for(uint32_t i=0;i<service_ids.size();++i) { RsServicePermissions serv_perm ; rsServiceControl->getServicePermissions(service_ids[i],serv_perm) ; QPixmap pix(global_switch[serv_perm.mDefaultAllowed].c_str()) ; QRect position = computeNodePosition(0,i,false) ; position.setY(position.y() - S*fICON_SIZE_Y + 8/14.0*S) ; position.setX(position.x() + 3/14.0*S) ; position.setHeight(30/14.0*S) ; position.setWidth(30/14.0*S) ; _painter->drawPixmap(position,pix.scaledToHeight(S*fICON_SIZE_Y*0.9,Qt::SmoothTransformation),QRect(0,0,S*fICON_SIZE_X,S*fICON_SIZE_Y)) ; } // We draw for each service. static const std::string pixmap_names[4] = { ":/icons/switch00_128.png", ":/icons/switch01_128.png", ":/icons/switch10_128.png", ":/icons/switch11_128.png" } ; int n_col = 0 ; int n_col_selected = -1 ; int n_row_selected = -1 ; for(std::map<uint32_t, RsServiceInfo>::const_iterator sit(ownServices.mServiceList.begin());sit!=ownServices.mServiceList.end();++sit,++n_col) { RsServicePermissions service_perms ; rsServiceControl->getServicePermissions(sit->first,service_perms) ; // draw the default switch. // draw one switch per friend. int n_row = 0 ; for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it,++n_row) { RsPeerServiceInfo local_service_perms ; RsPeerServiceInfo remote_service_perms ; rsServiceControl->getServicesAllowed (*it, local_service_perms) ; rsServiceControl->getServicesProvided(*it,remote_service_perms) ; bool local_allowed = local_service_perms.mServiceList.find(sit->first) != local_service_perms.mServiceList.end() ; bool remote_allowed = remote_service_perms.mServiceList.find(sit->first) != remote_service_perms.mServiceList.end() ; QPixmap pix(pixmap_names[(local_allowed << 1) + remote_allowed].c_str()) ; bool selected = (sit->first == _current_service_id && *it == _current_peer_id) ; QRect position = computeNodePosition(n_row,n_col,selected) ; if(selected) { n_row_selected = n_row ; n_col_selected = n_col ; } _painter->drawPixmap(position,pix.scaledToHeight(S*fICON_SIZE_X,Qt::SmoothTransformation),QRect(0,0,S*fICON_SIZE_X,S*fICON_SIZE_Y)) ; } } // now display some info about current node. if(n_row_selected >= 0 && n_col_selected >= 0 && n_row_selected < (int)peer_ids.size() && n_col_selected < (int)service_ids.size()) { QRect position = computeNodePosition(n_row_selected,n_col_selected,false) ; // draw text info RsServicePermissions service_perms ; rsServiceControl->getServicePermissions(service_ids[n_col_selected],service_perms) ; QString service_name = tr("Service name:")+" "+QString::fromUtf8(service_perms.mServiceName.c_str()) ; QString service_default = service_perms.mDefaultAllowed?tr("Allowed by default"):tr("Denied by default"); QString peer_name = tr("Peer name:")+" " + names[n_row_selected] ; QString peer_id = tr("Peer Id:")+" "+QString::fromStdString(_current_peer_id.toStdString()) ; RsPeerServiceInfo pserv_info ; rsServiceControl->getServicesAllowed(_current_peer_id,pserv_info) ; bool locally_allowed = pserv_info.mServiceList.find(_current_service_id) != pserv_info.mServiceList.end(); bool remotely_allowed = false ; // default, if the peer is offline if(rsServiceControl->getServicesProvided(_current_peer_id,pserv_info)) remotely_allowed = pserv_info.mServiceList.find(_current_service_id) != pserv_info.mServiceList.end(); QString local_status = locally_allowed ?tr("Enabled for this peer") :tr("Disabled for this peer") ; QString remote_status = remotely_allowed?tr("Enabled by remote peer"):tr("Disabled by remote peer") ; if(!service_perms.mDefaultAllowed) local_status = tr("Globally switched Off") ; const QFont& font(_painter->font()) ; QFontMetrics fm(font); int text_size_x = 0 ; text_size_x = std::max(text_size_x,fm.width(service_name)); text_size_x = std::max(text_size_x,fm.width(peer_name)); text_size_x = std::max(text_size_x,fm.width(peer_id)); text_size_x = std::max(text_size_x,fm.width(local_status)); text_size_x = std::max(text_size_x,fm.width(remote_status)); // draw a half-transparent rectangle QBrush brush ; brush.setColor(QColor::fromHsvF(0.0f,0.0f,1.0f,0.8f)); brush.setStyle(Qt::SolidPattern) ; QPen pen ; pen.setWidth(2) ; pen.setBrush(Qt::black) ; _painter->setPen(pen) ; QRect info_pos( position.x() + 50*S/14.0, position.y() - 10*S/14.0, text_size_x + 10*S/14.0, line_height * 5 + 5*S/14.0) ; _painter->fillRect(info_pos,brush) ; _painter->drawRect(info_pos) ; // draw the text float x = info_pos.x() + 5*S/14.0 ; float y = info_pos.y() + line_height + 1*S/14.0 ; _painter->drawText(QPointF(x,y), service_name) ; y += line_height ; _painter->drawText(QPointF(x,y), peer_name) ; y += line_height ; _painter->drawText(QPointF(x,y), peer_id) ; y += line_height ; _painter->drawText(QPointF(x,y), remote_status) ; y += line_height ; _painter->drawText(QPointF(x,y), local_status) ; y += line_height ; } _max_height = S*fMATRIX_START_Y + (peer_ids.size()+3) * S*fROW_SIZE ; _max_width = matrix_start_x + (service_ids.size()+3) * S*fCOL_SIZE ; /* Stop the painter */ _painter->end(); }
void OdClassInstCanvas::compute_size() { UmlCanvas * canvas = the_canvas(); ClassInstanceData * data = (ClassInstanceData *) browser_node->get_data(); used_color = (itscolor == UmlDefaultColor) ? canvas->browser_diagram()->get_color(UmlClass) : itscolor; switch (show_stereotype_properties) { case UmlYes: show_properties = TRUE; break; case UmlNo: show_properties = FALSE; break; default: // right arg set by the diagram itself show_properties = canvas->browser_diagram()->get_show_stereotype_properties(); } QFontMetrics fm(canvas->get_font(UmlNormalUnderlinedFont)); double zoom = canvas->zoom(); const int two = (int)(2 * zoom); int wi, he; horiz = TRUE; if (!get_name().isEmpty()) { switch (write_horizontally) { case UmlYes: horiz = TRUE; break; case UmlNo: horiz = FALSE; break; default: // right get_classinstwritehorizontally arg set by the diagram itself horiz = canvas->browser_diagram()->get_classinstwritehorizontally(); } } he = fm.height() + two + two; used_show_context_mode = (show_context_mode == DefaultShowContextMode) ? canvas->browser_diagram()->get_classinstshowmode() : show_context_mode; if (horiz) wi = fm.width(full_name()); else { he += fm.height(); int w = fm.width(get_name() + ":"); wi = fm.width(data->get_class()->contextual_name(used_show_context_mode)); if (w > wi) wi = w; } const Q3ValueList<SlotAttr> & attributes = data->get_attributes(); if (! attributes.isEmpty()) { Q3ValueList<SlotAttr>::ConstIterator it = attributes.begin(); QString egal = " = "; do { QString s = (*it).att->get_name() + egal + (*it).value; int w = fm.width(s); if (w > wi) wi = w; ++it; } while (it != attributes.end()); he += (fm.height() + two) * attributes.count() + two + two; } if (used_color != UmlTransparent) { const int shadow = canvas->shadow(); wi += shadow; he += shadow; } const int eight = (int)(8 * zoom); wi += (((ClassData *) data->get_class()->get_data())->get_is_active()) ? eight * 3 : eight; int minw = (int)(zoom * CLASSINST_CANVAS_MIN_SIZE); if (wi < minw) wi = minw; // force odd width and height for line alignment DiagramCanvas::resize(wi | 1, he | 1); }
void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (option.state & QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight()); } else if (option.state & QStyle::State_MouseOver) { QBrush brush(QColor(0, 0, 255, 25)); painter->fillRect(option.rect, brush); } Message msg = index.data(Qt::UserRole).value<Message>(); QStyleOptionViewItem myOption = option; QFontMetrics fm(painter->font()); int width = myOption.rect.width(); int height = myOption.rect.height(); int textMargin = fm.height(); Contact contact = g_phoneBook->getContactOfPhoneNum(msg.phonenum); QString str; if (contact.isValid()) { str = contact.name; } else { str = msg.phonenum; } myOption.displayAlignment = Qt::AlignCenter; QPixmap pixmap; QString strStatePix; switch (msg.state) { case Message::State_Read: strStatePix = ":/pic/Read.png"; break; case Message::State_Unread: strStatePix = ":/pic/Unread.png"; break; case Message::State_Unsend: strStatePix = ":/pic/Unsend.png"; break; case Message::State_Sent: strStatePix = ":/pic/Sent.png"; break; case Message::State_SendFail: strStatePix = ":/pic/SendFail.png"; break; default: qDebug() << "this is a bug" << __FILE__ << __LINE__; break; } pixmap.load(strStatePix); QSize sizePixmap(height / 2 * 0.7, height / 2 * 0.7); int pixMargin = (height/2-sizePixmap.height())/2; painter->drawPixmap(QRect(myOption.rect.topLeft() + QPoint(pixMargin, pixMargin), sizePixmap), pixmap); myOption.displayAlignment = Qt::AlignLeft | Qt::AlignVCenter; QSize sizeName(fm.width(msg.phonenum) + textMargin, height / 2); drawDisplay(painter, myOption, QRect(myOption.rect.topLeft() + QPoint(height/2, 0), sizeName), str); QSize sizeDateTime(width - sizePixmap.width() - sizeName.width(), height / 2); myOption.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; drawDisplay(painter, myOption, QRect(myOption.rect.topRight() - QPoint(sizeDateTime.width(), 0), sizeDateTime), msg.datetime.toString("yyyy-MM-dd hh:mm:ss")); myOption.displayAlignment = Qt::AlignLeft | Qt::AlignVCenter; drawDisplay(painter, myOption, QRect(option.rect.topLeft() + QPoint(height / 2, height / 2), QSize(option.rect.width() - height / 2, height / 2)), msg.content); }
void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (m_startItem->collidesWithItem(m_endItem)) return; painter->setBrush(m_color); qreal arrowSize = 12; double angle = ::acos(line().dx() / line().length()); if (line().dy() >= 0) angle = (Pi * 2) - angle; QPointF arrowP1 = line().p1() + QPointF(sin(angle + Pi / 3) * arrowSize, cos(angle + Pi / 3) * arrowSize); QPointF arrowP2 = line().p1() + QPointF(sin(angle + Pi - Pi / 3) * arrowSize, cos(angle + Pi - Pi / 3) * arrowSize); arrowHead.clear(); arrowHead << line().p1() << arrowP1 << arrowP2; painter->setPen(pen()); painter->drawLine(line()); painter->setPen(QPen(Qt::transparent)); painter->drawPolygon(arrowHead); painter->setPen(pen()); QString text; switch (m_status) { case PostMonster::Ok: text = QStringLiteral("OK"); break; case PostMonster::Fail: text = QStringLiteral("FAIL"); break; default: break; } painter->setFont(QFont("sans", 8)); QFontMetrics fm(painter->font()); int textWidth = fm.width(text); if (textWidth * 3 > line().length()) return; if (angle > Pi / 2 && angle < 3 * Pi / 2) angle += Pi; QPointF textP = (line().p1() + line().p2()) / 2; painter->save(); painter->translate(textP); painter->rotate(-angle * 180 / Pi); painter->drawText(QPointF(-textWidth / 2, -5), text); painter->restore(); /*if (isSelected()) { painter->setPen(QPen(m_color, 1, Qt::DashLine)); QLineF myLine = line(); myLine.translate(0, 4.0); painter->drawLine(myLine); myLine.translate(0,-8.0); painter->drawLine(myLine); }*/ }
QSize ResultScene::minimumSizeHint() const { QFontMetrics fm(font()); return QSize(KIconLoader::SizeMedium * 4, (fm.height() * 5) * 3); }
KexiRecordNavigator::KexiRecordNavigator(QWidget *parent, Q3ScrollView* parentView, int leftMargin) : QWidget(parent) , d(new Private) { setAutoFillBackground(true); setFocusPolicy(Qt::NoFocus); if (parentView) setParentView(parentView); d->lyr = new QHBoxLayout(this); // const bool winStyle = style()->objectName().toLower() == "windows"; // used to fix appearance of the number field d->lyr->setContentsMargins(0, /*winStyle ? 1 :*/ 0, 0, 0); d->lyr->setSpacing(2); d->textLabel = new QLabel(this); d->lyr->addWidget(d->textLabel); setLabelText(i18n("Row:")); setFont( KexiUtils::smallFont() ); QFontMetrics fm(font()); d->nav1DigitWidth = fm.width("8"); d->navBtnFirst = createAction(KexiRecordNavigator::Actions::moveToFirstRecord()); d->navBtnPrev = createAction(KexiRecordNavigator::Actions::moveToPreviousRecord()); d->navBtnPrev->setAutoRepeat(true); d->lyr->addSpacing(2); d->navRecordNumber = new KLineEdit(this); d->lyr->addWidget(d->navRecordNumber, 0, Qt::AlignVCenter); KexiUtils::WidgetMargins margins; // margins.top = winStyle ? 1 : 0; // margins.bottom = winStyle ? 1 : 0; margins.copyToWidget(d->navRecordNumber); d->navRecordNumber->setFrame(false); if (parentView) { kDebug() << parentView->horizontalScrollBar()->height(); d->navRecordNumber->setFixedHeight( qMax(parentView->bottomMargin(), fm.height() + 2) ); } d->navRecordNumber->setAlignment(Qt::AlignRight | (/*winStyle ? Qt::AlignBottom :*/ Qt::AlignVCenter)); d->navRecordNumber->setFocusPolicy(Qt::ClickFocus); d->navRecordNumberValidator = new QIntValidator(1, INT_MAX, this); d->navRecordNumber->setValidator(d->navRecordNumberValidator); d->navRecordNumber->installEventFilter(this); d->navRecordNumber->setToolTip(i18n("Current row number")); QLabel *lbl_of = new QLabel(i18nc("\"of\" in row number information: N of M", "of"), this); lbl_of->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); lbl_of->setFixedWidth(fm.width(lbl_of->text()) + d->nav1DigitWidth); lbl_of->setAlignment(Qt::AlignCenter); d->lyr->addWidget(lbl_of, 0, Qt::AlignVCenter); d->navRecordCount = new KLineEdit(this); d->lyr->addWidget(d->navRecordCount, 0, Qt::AlignVCenter); // d->navRecordCount->setTextInteractionFlags(Qt::TextSelectableByMouse); d->navRecordCount->setFrame(false); d->navRecordCount->setReadOnly(true); QPalette navRecordCountPalette(d->navRecordCount->palette()); // navRecordCountPalette.setBrush( QPalette::Base, navRecordCountPalette.brush(QPalette::Window) ); navRecordCountPalette.setBrush( QPalette::Base, QBrush(Qt::transparent) ); d->navRecordCount->setPalette(navRecordCountPalette); if (parentView) { d->navRecordCount->setFixedHeight( qMax(parentView->bottomMargin(), fm.height() + 2) ); } d->navRecordCount->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); d->navRecordCount->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); d->navRecordCount->setFocusPolicy(Qt::NoFocus); d->navRecordCount->setToolTip(i18n("Number of rows")); d->navBtnNext = createAction(KexiRecordNavigator::Actions::moveToNextRecord()); d->navBtnNext->setAutoRepeat(true); d->navBtnLast = createAction(KexiRecordNavigator::Actions::moveToLastRecord()); d->lyr->addSpacing(2); d->navBtnNew = createAction(KexiRecordNavigator::Actions::moveToNewRecord()); d->navBtnNew->setEnabled(isInsertingEnabled()); d->lyr->addSpacing(6); d->lyr->addStretch(10); connect(d->navBtnPrev, SIGNAL(clicked()), this, SLOT(slotPrevButtonClicked())); connect(d->navBtnNext, SIGNAL(clicked()), this, SLOT(slotNextButtonClicked())); connect(d->navBtnLast, SIGNAL(clicked()), this, SLOT(slotLastButtonClicked())); connect(d->navBtnFirst, SIGNAL(clicked()), this, SLOT(slotFirstButtonClicked())); connect(d->navBtnNew, SIGNAL(clicked()), this, SLOT(slotNewButtonClicked())); setRecordCount(0); setCurrentRecordNumber(0); updateGeometry(leftMargin); }
void RadialMap::Widget::paintExplodedLabels(QPainter &paint) const { //we are a friend of RadialMap::Map LabelList list; list.setAutoDelete(true); Q3PtrListIterator<Label> it(list); unsigned int startLevel = 0; //1. Create list of labels sorted in the order they will be rendered if (m_focus && m_focus->file() != m_tree) //separate behavior for selected vs unselected segments { //don't bother with files if (m_focus->file() && !m_focus->file()->isDirectory()) return; //find the range of levels we will be potentially drawing labels for //startLevel is the level above whatever m_focus is in for (const Directory *p = (const Directory*)m_focus->file(); p != m_tree; ++startLevel) p = p->parent(); //range=2 means 2 levels to draw labels for unsigned int a1, a2, minAngle; a1 = m_focus->start(); a2 = m_focus->end(); //boundry angles minAngle = int(m_focus->length() * LABEL_MIN_ANGLE_FACTOR); #define segment (*it) #define ring (m_map.m_signature + i) //**** Levels should be on a scale starting with 0 //**** range is a useless parameter //**** keep a topblock var which is the lowestLevel OR startLevel for identation purposes for (unsigned int i = startLevel; i <= m_map.m_visibleDepth; ++i) for (Iterator<Segment> it = ring->iterator(); it != ring->end(); ++it) if (segment->start() >= a1 && segment->end() <= a2) if (segment->length() > minAngle) list.inSort(new Label(segment, i)); #undef ring #undef segment } else { #define ring m_map.m_signature for (Iterator<Segment> it = ring->iterator(); it != ring->end(); ++it) if ((*it)->length() > 288) list.inSort(new Label((*it), 0)); #undef ring } //2. Check to see if any adjacent labels are too close together // if so, remove the least significant labels it.toFirst(); Q3PtrListIterator<Label> jt(it); ++jt; while (jt) //**** no need to check _it_ as jt will be NULL if _it_ was too { //this method is fairly efficient if ((*it)->tooClose((*jt)->a)) { if ((*it)->lvl > (*jt)->lvl) { list.remove(*it); it = jt; } else list.remove(*jt); } else ++it; jt = it; ++jt; } //used in next two steps bool varySizes; //**** should perhaps use doubles int *sizes = new int [ m_map.m_visibleDepth + 1 ]; //**** make sizes an array of floats I think instead (or doubles) do { //3. Calculate font sizes { //determine current range of levels to draw for uint range = 0; for (it.toFirst(); it != 0; ++it) { uint lvl = (*it)->lvl; if (lvl > range) range = lvl; //**** better way would just be to assign if nothing is range } range -= startLevel; //range 0 means 1 level of labels varySizes = Config::varyLabelFontSizes && (range != 0); if (varySizes) { //create an array of font sizes for various levels //will exceed normal font pitch automatically if necessary, but not minPitch //**** this needs to be checked lots //**** what if this is negative (min size gtr than default size) uint step = (paint.font().pointSize() - Config::minFontPitch) / range; if (step == 0) step = 1; for (uint x = range + startLevel, y = Config::minFontPitch; x >= startLevel; y += step, --x) sizes[x] = y; } } //4. determine label co-ordinates int x1, y1, x2, y2, x3, tx, ty; //coords double sinra, cosra, ra; //angles int cx = m_map.width() / 2 + m_offset.x(); //centre relative to canvas int cy = m_map.height() / 2 + m_offset.y(); int spacer, preSpacer = int(m_map.m_ringBreadth * 0.5) + m_map.m_innerRadius; int fullStrutLength = (m_map.width() - m_map.MAP_2MARGIN) / 2 + LABEL_MAP_SPACER; //full length of a strut from map center int prevLeftY = 0; int prevRightY = height(); bool rightSide; QFont font; for (it.toFirst(); it != 0; ++it) { //** bear in mind that text is drawn with QPoint param as BOTTOM left corner of text box QString qs = (*it)->segment->file()->name(); if (varySizes) font.setPointSize(sizes[(*it)->lvl]); QFontMetrics fm(font); int fmh = fm.height(); //used to ensure label texts don't overlap int fmhD4 = fmh / 4; fmh += LABEL_TEXT_VMARGIN; rightSide = ((*it)->a < 1440 || (*it)->a > 4320); ra = M_PI/2880 * (*it)->a; //convert to radians sincos(ra, &sinra, &cosra); spacer = preSpacer + m_map.m_ringBreadth * (*it)->lvl; x1 = cx + (int)(cosra * spacer); y1 = cy - (int)(sinra * spacer); y2 = y1 - (int)(sinra * (fullStrutLength - spacer)); if (rightSide) { //righthand side, going upwards if (y2 > prevRightY /*- fmh*/) //then it is too low, needs to be drawn higher y2 = prevRightY /*- fmh*/; } else //lefthand side, going downwards if (y2 < prevLeftY/* + fmh*/) //then we're too high, need to be drawn lower y2 = prevLeftY /*+ fmh*/; x2 = x1 - int(double(y2 - y1) / tan(ra)); ty = y2 + fmhD4; if (rightSide) { if (x2 > width() || ty < fmh || x2 < x1) { //skip this strut //**** don't duplicate this code list.remove(*it); //will delete the label and set it to list.current() which _should_ be the next ptr break; } prevRightY = ty - fmh - fmhD4; //must be after above's "continue" qs = fm.elidedText(qs, Qt::ElideMiddle, width() - x2); x3 = width() - fm.width(qs) - LABEL_HMARGIN //outer margin - LABEL_TEXT_HMARGIN //margin between strut and text //- ((*it)->lvl - startLevel) * LABEL_HMARGIN; //indentation ; if (x3 < x2) x3 = x2; tx = x3 + LABEL_TEXT_HMARGIN; } else { if (x2 < 0 || ty > height() || x2 > x1) { //skip this strut list.remove(*it); //will delete the label and set it to list.current() which _should_ be the next ptr break; } prevLeftY = ty + fmh - fmhD4; qs = fm.elidedText(qs, Qt::ElideMiddle, x2); //**** needs a little tweaking: tx = fm.width(qs) + LABEL_HMARGIN/* + ((*it)->lvl - startLevel) * LABEL_HMARGIN*/; if (tx > x2) { //text is too long tx = LABEL_HMARGIN + x2 - tx; //some text will be lost from sight x3 = x2; //no text margin (right side of text here) } else { x3 = tx + LABEL_TEXT_HMARGIN; tx = LABEL_HMARGIN /*+ ((*it)->lvl - startLevel) * LABEL_HMARGIN*/; } } (*it)->x1 = x1; (*it)->y1 = y1; (*it)->x2 = x2; (*it)->y2 = y2; (*it)->x3 = x3; (*it)->tx = tx; (*it)->ty = ty; (*it)->qs = qs; } //if an element is deleted at this stage, we need to do this whole //iteration again, thus the following loop //**** in rare case that deleted label was last label in top level // and last in labelList too, this will not work as expected (not critical) } while (it != 0); //5. Render labels paint.setPen(QPen(Qt::black, 1)); for (it.toFirst(); it != 0; ++it) { if (varySizes) { //**** how much overhead in making new QFont each time? // (implicate sharing remember) QFont font = paint.font(); font.setPointSize(sizes[(*it)->lvl]); paint.setFont(font); } paint.drawEllipse((*it)->x1 - 3, (*it)->y1 - 3, 7, 7); //**** CPU intensive! better to use a pixmap paint.drawLine((*it)->x1, (*it)->y1, (*it)->x2, (*it)->y2); paint.drawLine((*it)->x2, (*it)->y2, (*it)->x3, (*it)->y2); paint.drawText((*it)->tx, (*it)->ty, (*it)->qs); } delete [] sizes; }
MsgEdit::MsgEdit(QWidget *parent, UserWnd *userWnd) : QMainWindow(parent, NULL, 0) { m_userWnd = userWnd; m_msg = NULL; m_bTyping = false; m_type = NO_TYPE; m_flags = 0; m_retry.msg = NULL; m_bReceived = false; m_processor = NULL; m_recvProcessor = NULL; m_cmd.param = NULL; connect(CorePlugin::m_plugin, SIGNAL(modeChanged()), this, SLOT(modeChanged())); m_frame = new QFrame(this, "msgedit"); setCentralWidget(m_frame); m_layout = new QVBoxLayout(m_frame); m_edit = new MsgTextEdit(this, m_frame); m_edit->setBackground(QColor(CorePlugin::m_plugin->getEditBackground() & 0xFFFFFF)); m_edit->setForeground(QColor(CorePlugin::m_plugin->getEditForeground() & 0xFFFFFF), true); m_edit->setFont(CorePlugin::m_plugin->editFont); m_edit->setCtrlMode(!CorePlugin::m_plugin->getSendOnEnter()); m_edit->setParam(this); setFocusProxy(m_edit); QStyleSheet *style = new QStyleSheet(m_edit); QStyleSheetItem *style_p = style->item("p"); // Disable top and bottom margins for P tags. This will make sure // paragraphs have no more spacing than regular lines, thus matching // RTFs defaut look for paragraphs. style_p->setMargin(QStyleSheetItem::MarginTop, 0); style_p->setMargin(QStyleSheetItem::MarginBottom, 0); m_edit->setStyleSheet(style); connect(m_edit, SIGNAL(lostFocus()), this, SLOT(editLostFocus())); connect(m_edit, SIGNAL(textChanged()), this, SLOT(editTextChanged())); connect(m_edit, SIGNAL(ctrlEnterPressed()), this, SLOT(editEnterPressed())); connect(m_edit, SIGNAL(colorsChanged()), this, SLOT(colorsChanged())); connect(m_edit, SIGNAL(finished()), this, SLOT(editFinished())); connect(m_edit, SIGNAL(fontSelected(const QFont&)), this, SLOT(editFontChanged(const QFont&))); QFontMetrics fm(m_edit->font()); m_edit->setMinimumSize(QSize(fm.maxWidth(), fm.height() + 10)); m_layout->addWidget(m_edit); BarShow b; b.bar_id = ToolBarMsgEdit; b.parent = this; Event e(EventShowBar, &b); m_bar = (CToolBar*)(e.process()); m_bar->setParam(this); if (CorePlugin::m_plugin->getContainerMode() == 0) showCloseSend(false); setDockEnabled(m_bar, Left, false); setDockEnabled(m_bar, Right, false); }
void InstrItem::updateCost() { _pure = SubCost(0); _pure2 = SubCost(0); if (!_instr) return; if (_instrJump) return; ProfileCostArray* instrCost = _instrCall ? (ProfileCostArray*)_instrCall : (ProfileCostArray*)_instr; // do not show any cost inside of cycles if (_instrCall && ((_instrCall->call()->inCycle()>0) || (_instrCall->call()->isRecursion()))) { QString str; QPixmap p; QFontMetrics fm(font(1)); p = QIcon::fromTheme(QStringLiteral("edit-undo")).pixmap(fm.height()); if (p.isNull()) str = QObject::tr("(cycle)"); setText(1, str); setIcon(1, p); setText(2, str); setIcon(2, p); return; } ProfileCostArray* totalCost; if (GlobalConfig::showExpanded()) totalCost = _instr->function()->inclusive(); else totalCost = _instr->function()->data(); EventType *et = _view->eventType(); _pure = et ? instrCost->subCost(et) : SubCost(0); if (_pure == 0) { setText(1, QString()); setIcon(1, QPixmap()); } else { double total = totalCost->subCost(et); double pure = 100.0 * _pure / total; if (GlobalConfig::showPercentage()) setText(1, QStringLiteral("%1") .arg(pure, 0, 'f', GlobalConfig::percentPrecision())); else setText(1, _pure.pretty()); setIcon(1, costPixmap(et, instrCost, total, false)); } EventType *ct2 = _view->eventType2(); _pure2 = ct2 ? instrCost->subCost(ct2) : SubCost(0); if (_pure2 == 0) { setText(2, QString()); setIcon(2, QPixmap()); } else { double total = totalCost->subCost(ct2); double pure = 100.0 * _pure2 / total; if (GlobalConfig::showPercentage()) setText(2, QStringLiteral("%1") .arg(pure, 0, 'f', GlobalConfig::percentPrecision())); else setText(2, _pure2.pretty()); setIcon(2, costPixmap(ct2, instrCost, total, false)); } }
void OverlayHandler::showText(const QString &text, QFont font, QColor color, QPoint pos, int duration, int id) { // increase next overlay_id if(id == -1) // auto id { id = overlay_id; if(overlay_id+1 > max_overlay) overlay_id = min_overlay; else ++overlay_id; } QFontMetrics fm(font); QStringList lines = text.split('\n'); // the 1.3 was pretty much determined through trial and error; this formula isn't perfect // apparently, QFontMetrics doesn't work that well const float fm_correction = 1.3; int w = 0, h = fm.height()*lines.length(); for(auto line : lines) w = std::max(fm.width(line), w); float xF = float(baka->window->ui->mpvFrame->width()-2*pos.x()) / (fm_correction*w); float yF = float(baka->window->ui->mpvFrame->height()-2*pos.y()) / h; font.setPointSizeF(std::min(font.pointSizeF()*std::min(xF, yF), font.pointSizeF())); fm = QFontMetrics(font); h = fm.height(); w = 0; QPainterPath path(QPoint(0, 0)); QPoint p = QPoint(0, h); for(auto line : lines) { path.addText(p, font, line); w = std::max(int(fm_correction*path.currentPosition().x()), w); p += QPoint(0, h); } QImage *canvas = new QImage(w, p.y(), QImage::Format_ARGB32); // make the canvas the right size canvas->fill(QColor(0,0,0,0)); // fill it with nothing QPainter painter(canvas); // prepare to paint painter.setRenderHint(QPainter::Antialiasing); painter.setCompositionMode(QPainter::CompositionMode_Overlay); painter.setFont(font); painter.setPen(QColor(0, 0, 0)); painter.setBrush(color); painter.drawPath(path); // add as mpv overlay baka->mpv->AddOverlay( id == -1 ? overlay_id : id, pos.x(), pos.y(), "&"+QString::number(quintptr(canvas->bits())), 0, canvas->width(), canvas->height()); // add over mpv as label QLabel *label = new QLabel(baka->window->ui->mpvFrame); label->setStyleSheet("background-color:rgb(0,0,0,0);background-image:url();"); label->setGeometry(pos.x(), pos.y(), canvas->width(), canvas->height()); label->setPixmap(QPixmap::fromImage(*canvas)); label->show(); QTimer *timer; if(duration == 0) timer = nullptr; else { timer = new QTimer(this); timer->start(duration); connect(timer, &QTimer::timeout, // on timeout [=] { remove(id); }); } overlay_mutex.lock(); if(overlays.find(id) != overlays.end()) delete overlays[id]; overlays[id] = new Overlay(label, canvas, timer, this); overlay_mutex.unlock(); }
format * mk_choice(ast_manager & m, format * f1, format * f2) { return fm(m).mk_app(fid(m), OP_CHOICE, f1, f2); }