不是我想在我的Qt小部件上显示

不是我想在我的Qt小部件上显示

本文介绍了为什么“矩形”不是我想在我的Qt小部件上显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想在对话框窗口小部件上显示一个矩形。使用另一个问题作为参考,我尝试调整使用QLabel并对其进行绘画的框架(整个过程似乎过于复杂)。

I basically want to display a rectangle on a dialog window widget. Using another question as reference, I tried to adapt the framework of using a QLabel and painting to it (the process overall seems overly complicated).

我首先在对话框的类中成为成员:

I started by making a member in the dialog box's class:

QLabel* label;

在对话框的构造函数中:

In the constructor of the dialog box:

label = new QLabel(this);
label->setGeometry(20, 50, 50, 100);

只是尝试使其工作,我为对话框提供了一个按钮以使矩形使用标签创建的标签将显示在小部件上。我将这个按钮的按下信号连接到执行以下操作的插槽上:

Just to try and make it work, I gave the dialog box a button to make the "rectangle" created with the label appear on the widget. I connected the "pressed" signal of this button to a slot which does the following:

QPixmap pixmap(50, 100);
pixmap.fill(QColor("transparent"));
QPainter painter(&pixmap);
painter.setBrush(QBrush(Qt::black));
painter.drawRect(20, 50, 50, 100);
label->setPixmap(pixmap);
update();

不幸的是,当我按下按钮时,小部件中什么也没有出现。我在这里想念什么?

Unfortunately, nothing appears in the widget when I press the button. What am I missing here?

推荐答案

我在PyQt上尝试了此方法,该方法通常可以使用,但我不确定100%是否可以执行此操作。也许您应该在调用 setPixmap()之前尝试调用 painter.end()画家。另外,我不确定是否应该在 QWidget:paintEvent 之外绘制QPixmap,绘制QImage并从中创建QPixmap可能更安全。

I tried this with PyQt and it generally works, but I'm not 100% sure about the procedure. Maybe you should try calling painter.end() the painter before calling setPixmap(). Also, I'm not sure if one is supposed to draw onto a QPixmap outside of QWidget:paintEvent, it might be safer to draw a QImage and create a QPixmap from it.

from PyQt4 import QtGui

app = QtGui.QApplication([])

class Test(QtGui.QWidget):
    def __init__(self):
       QtGui.QWidget.__init__(self)
       self.bn = QtGui.QPushButton("Paint")
       self.lb = QtGui.QLabel()
       layout = QtGui.QVBoxLayout(self)
       layout.addWidget(self.bn)
       layout.addWidget(self.lb)
       self.bn.clicked.connect(self.handleClick)

    def handleClick(self):
       pixmap = QtGui.QPixmap(50, 100)
       pixmap.fill(QtGui.QColor("transparent"))
       p = QtGui.QPainter(pixmap)
       p.drawRect(0,0,50-1,100-1)
       p.end()
       self.lb.setPixmap(pixmap)

t = Test()
t.show()
app.exec_()

对于s暗示画一个矩形,这当然是非常复杂的。我不知道您在计划什么,请注意,有QGraphicsView用于绘制图形。

For simply drawing a rectangle this is certainly very complicated. I don't know what you are planning, be aware that there is QGraphicsView for drawing figures.

这篇关于为什么“矩形”不是我想在我的Qt小部件上显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:31