[qt] QLabel : 텍스트 및 배경색 설정

텍스트의 색상과 배경을 어떻게 설정 QLabel합니까?



답변

가장 권장되는 방법은 Qt 스타일 시트 를 사용하는 것입니다 .

의 텍스트 색상과 배경색을 변경하려면 다음과 같이 QLabel하십시오.

QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");

Qt 스타일 시트를 사용하지 않고 QPalette색상을 변경할 QLabel수도 있지만 플랫폼 및 스타일에 따라 결과가 다를 수 있습니다.

Qt 문서에 따르면 :

스타일 작성자가 다른 플랫폼의 지침과 기본 테마 엔진에 의해 제한되기 때문에 QPalette를 사용한다고해서 모든 스타일에 적용되는 것은 아닙니다.

그러나 다음과 같이 할 수 있습니다.

 QPalette palette = ui->pLabel->palette();
 palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
 palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
 ui->pLabel->setPalette(palette);

그러나 내가 말했듯이 팔레트를 사용하지 말고 Qt 스타일 시트를 사용하는 것이 좋습니다.


답변

QPalette를 사용할 수 있지만 setAutoFillBackground(true);배경색을 활성화하도록 설정 해야합니다

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

그것은 Windows와 Ubuntu에서 잘 작동하며 다른 OS와 함께 연주하지 않았습니다.

참고 : 자세한 내용은 색상 역할 섹션 인 QPalette 를 참조하십시오.


답변

나는 누군가에게 유용 할 수 있다고 생각하기 때문에이 대답을 추가합니다.

페인팅 응용 프로그램의 컬러 디스플레이 레이블에 RGBA 색상 (투명도에 대한 알파 값을 가진 RGB 색상) 을 설정하는 문제를 겪습니다 .

첫 번째 답변을 보았을 때 RGBA 색상을 설정할 수 없었습니다. 나는 또한 다음과 같은 것을 시도했다.

myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())

colorRGBA 색상은 어디에 있습니까 ?

그래서 내 더러운 해결책은 경계 수정을 채우는 방법 을 확장 QLabel하고 재정의 paintEvent()하는 것이 었습니다 .

오늘은를 열고 스타일 참조 속성 목록을qt-assistant 읽었 습니다 . 불행히도 다음과 같은 예가 있습니다.

QLineEdit { background-color: rgb(255, 0, 0) }

이것으로 예를 들어 아래 코드와 같은 일을 할 수 있습니다.

myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color  = QtGui.QColor(233, 10, 150)
alpha  = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
                                     g = color.green(),
                                     b = color.blue(),
                                     a = alpha
                                     )
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")

그 주 setAutoFillBackground()에서 설정 False이 작동하지 않습니다를.

문안 인사,


답변

나를 위해 일한 유일한 것은 html이었습니다.

그리고 나는 프로그래밍 방식보다 훨씬 쉽다는 것을 알았습니다.

다음 코드는 호출자가 전달한 매개 변수에 따라 텍스트 색상을 변경합니다.

enum {msg_info, msg_notify, msg_alert};
:
:
void bits::sendMessage(QString& line, int level)
{
    QTextCursor cursor = ui->messages->textCursor();
    QString alertHtml  = "<font color=\"DeepPink\">";
    QString notifyHtml = "<font color=\"Lime\">";
    QString infoHtml   = "<font color=\"Aqua\">";
    QString endHtml    = "</font><br>";

    switch(level)
    {
        case msg_alert:  line = alertHtml % line; break;
        case msg_notify: line = notifyHtml % line; break;
        case msg_info:   line = infoHtml % line; break;
        default:         line = infoHtml % line; break;
    }

    line = line % endHtml;
    ui->messages->insertHtml(line);
    cursor.movePosition(QTextCursor::End);
    ui->messages->setTextCursor(cursor);
}


답변

위젯의 색상과 관련된 기능을 설정하는 가장 좋은 방법은 QPalette 를 사용하는 입니다.

그리고 당신이 찾고있는 것을 찾는 가장 쉬운 방법은 Qt Designer를 열고 QLabel의 팔레트를 설정하고 생성 된 코드를 확인하는 것입니다.


답변

이건 완벽 해

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor()메소드는 선택된 색상을 반환합니다. 라벨 색상을 사용하여 변경할 수 있습니다stylesheet


답변